I have created a CustomValidator control
public class MyValidator :CustomValidator, IScriptControl {}
and also created the equivalent client script. The server validation works fine, however how do I hook up my client script?
The rendered javascript looks like
var MyValidator1 = document.all ? document.all["MyValidator1"] : document.getElementById("MyValidator1");
MyValidator1.controltovalidate = "MyField";
MyValidator1.errormessage = "error";
MyValidator1.evaluationfunction = "MyValidatorEvaluateIsValid";
How do I override the generated javascript to set the value of evaluationfunction? E.g.
MyValidator1.evaluationfunction = "MyCustomJavascriptFunction";
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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";
Method 2
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";
Method 3
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;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0