How do I hook up javascript to my CustomValidator control in .Net

大城市里の小女人 提交于 2019-12-02 08:46:00

You can set the ClientValidationFunction property of the base class like this -

base.ClientValidationFunction = "MyCustomJavascriptFunction";

So, it will render it like this -

MyValidator1.evaluationfunction = "MyCustomJavascriptFunction";

You can do it from the control also by setting the same property.

EDIT: You can do

document.getElementById("<%= ValidatorId %>").evaluationfunction = "MyCustomJavascriptFunction";

I've answered this myself as the other answer didn't quite achieve exactly what I wanted. I ended up using.

public class MyValidator : BaseValidator, IScriptControl  {

  protected override void AddAttributesToRender(HtmlTextWriter writer) {
    base.AddAttributesToRender(writer);
    Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "MyJavascriptFunction");
  }

}

Which will cause the control to generate:

MyValidator1.evaluationfunction = "MyJavascriptFunction";

Actually much easier is to use the ClientValidationFunction property of the asp:CustomValidator like below. Be sure NOT to specify a ControlToValidate property.

<asp:CustomValidator ClientValidationFunction="MyCustomJSFunction" Text="Required" ForeColor="Red"></asp:CustomValidator>

function MyCustomJSFunction(validator, args) {
    args.IsValid = my condition;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!