When using ASP. in Web Forms development, some drop-down controls are sometimes added with custom verification. However, due to the inertia of Validator, The ControlToValidate attribute is often set, as shown in the following code:
[Html]
<Asp: DropDownList ID = "DropDownList1" runat = "server">
</Asp: DropDownList>
<Asp: CustomValidator ID = "cvDdlGames" runat = "server" ClientValidationFunction = "ValidateGames" ControlToValidate = "DropDownList1"
ErrorMessage = "Incorrect content" Display = "Dynamic"> </asp: CustomValidator>
If the custom verification control does not work after this attribute is set, and the script execution process is tracked in the browser and the custom verification method ValidateGames is not executed, why?
It depends on the JS script that comes with asp.net. Through tracking, we find that the final method to call the custom method ValidateGames is mmvalidatorevaluateisvalid, as shown below:
[Javascript]
Function CustomValidatorEvaluateIsValid (val ){
Var value = "";
If (typeof (val. controltovalidate) = "string "){
// If the ControlToValidate attribute is set, it will enter here
Value = ValidatorGetValue (val. controltovalidate); // obtain the value of the associated control. If it is TextBox, the value can be obtained here, so there is no problem, but if you want the DeropdownList control, the value obtained here is null.
If (ValidatorTrim (value). length = 0 )&&
(Typeof (val. validateemptytext )! = "String") | (val. validateemptytext! = "True "))){
Return true; // The returned result is returned in advance.
}
}
Var args = {Value: value, IsValid: true };
If (typeof (val. clientvalidationfunction) = "string "){
Eval (val. clientvalidationfunction + "(val, args );");
}
Return args. IsValid;
}
Therefore, when using CustomValidator to verify the DropDownList control, do not set the ControlToValidate attribute. Although this attribute is not set, it does not affect its use, it will still block the submission of the current page (when there is a logic error in the data), so you can use it with confidence.
This is an excerpt from Bian Cheng's column.