In this post Disable asp.net validation controls in JavaScript;
we will see on how to disable Asp.Net validation controls using JavaScript.
Asp.net validation controls are server side controls,
but we might need to disabled them at times, these controls can be disabled
from the server side code using the .Enabled property as follows.
validateName.Enabled = false;
But, disabling the controls from the code-behind will
require a page post back; to avoid this we can disable the Validation controls
from the client side using Java Script as follows.
var myValidator = document.getElementById('validateName');
ValidatorEnable(myValidator,
false);
You might wonder that we have not defined the function ValidatorEnable, and might throw an error,
but no errors will be thrown, this is a Built in function in Asp.Net
Here is a full example
<script type="text/javascript">
function DisableValidator(checked)
{
if (checked
== true)
{
var
myValidator = document.getElementById('validateName');
ValidatorEnable(myValidator, false);
}
}
</script>
Enter
Name:
<asp:TextBox
ID="txtName"
runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="validateName"
runat="server"
ControlToValidate="txtName"
ErrorMessage=" Please enter Name"
Display="Dynamic">
</asp:RequiredFieldValidator><br />
Disable
Validator:
<input
type="checkbox"
value="Disable Validator"
onclick="javascript:DisableValidator(this.checked);"
/><br
/>
<asp:Button
ID="cmdSave"
runat="server"
Text="Save" onclick="cmdSave_Click"/>
In the above example when the
Disable Validator checkbox is checked, the validator validateName is disable, hence the user can submit the
form without entering the name, but when the checkbox is not checked the user
is prompted with an error message Please enter Name,
when the txtName TextBox is empty
No comments:
Post a Comment