Enable / Disable ASP.Net Validators using JavaScript

Posted: October 23, 2010 in Asp.net

Aspx Page:

UserName: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valName" ValidationGroup = "Group1"
    ControlToValidate = "txtName" runat="server" ErrorMessage="*Required" />
<br />
Enable Validation: <input type = "checkbox" id = "chk" onclick = "ToggleValidator(this);" />
<br />
<input id="btnSave" type="button" value="Save" onclick = "VerifyAndSave()" />

JavaScript:

<script type = "text/javascript">
    function VerifyAndSave() {
        if (typeof (Page_ClientValidate) == ‘function’) {
            Page_ClientValidate();
        }
        if (Page_IsValid) {
            alert("Validations successful");
            //do something
        }
    }
    function ToggleValidator(chk) {
        var valName = document.getElementById("<%=valName.ClientID%>");
        if (chk.checked) {
            ValidatorEnable(valName, true);
        }
        else {
            ValidatorEnable(valName, false);
        }
    }
</script>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s