We can validate text boxs straight away using the onblur event handler. When we add this event handler to our text boxs and text areas the appropriate validation routine will be called as soon as the person moves on to another field.
Of course we will still need to validate the same field immediately prior to submitting the form just in case someone bypasses accessing the field at all. We can easily add the same validation to both places by placing all of the code for the validation into a function and calling that function from both places.
Here is what the code for a text boxlooks like with the validation processing added:
<asp:TextBox ID="txtEmail" runat="server" onblur="ValidateControl(this)" ></asp:TextBox>
<asp:RequiredFieldValidator ID="reqTxtEmail" runat="server" SetFocusOnError="true"
ControlToValidate="txtEmail" ErrorMessage=" required" EnableClientScript="true" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" SetFocusOnError="true" ControlToValidate="txtEmail" ErrorMessage=" invalid"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ></asp:RegularExpressionValidator>
In this example ValidateControl(this) is called OnBlur of the TextBox. This method finds all validator controls for this text box in Page_Validators array, then call ValidatorValidate function of Asp.Net to validate. Javascript to validate is,
function ValidateControl(controltovalidate) {
if (typeof (Page_Validators) != "undefined") {
for (i = 0; i < Page_Validators.length; i++) {
val = Page_Validators[i];
if (val.controltovalidate == controltovalidate.id) {
ValidatorValidate(val);
if (val.isvalid==false) {
return;
}
}
}
}
}



No comments:
Post a Comment