We often provide form reset functionality, and people handle it client-side or server-side. Generally, we validate user input and show the proper validation messages. But sometimes, the user has entered the wrong information, and thus it will display validation messages. Now, if you have handled form reset functionality client-side, you must also reset all validation messages. You can do it as shown in the below code:
Javascript:
function ResetForm() {
$('input[type=text], textarea').val('');
Page_ClientValidateReset();
return false;
}
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
HTML:
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClientClick="return ResetForm();" />
Now let’s understand what JavaScript properties and functions are.
Page_Validators: This array contains all the validators on the page.
isvalid: This is a property on each client validator indicating whether it is currently valid.
ValidatorUpdateDisplay: Inbuilt function which checks whether the validation control’s display property is dynamic; if yes, then it will set the CSS style of that validator to none.
So basically, it loops through all the validators, sets isvalid property to true and set validators’ visibility to none. Here we’re not using the form reset function to clear form fields as Reset doesn’t clear a form; it simply sets the form value to its default which may or may not be blank.
I hope it helps!
Leave a Reply