Home > ASP .Net, c# > RequiredFieldValidator conditional validation via client side script

RequiredFieldValidator conditional validation via client side script

Interesting Problem.

I created a user edit page on an ASP.Net website. A user when looking at their own record got a “Change Password” panel. It is optional and only updated if data is entered in the text boxes. I wanted to use the CompareValidator to compare the txtPassword and txtConfirmPassword textboxes.

This worked great, I set up the CompareValidator to validate the txtConfirmPassword against the txtPassword. Problem is the ConfirmValidator does not fire when there is nothing entered in the txtConfirmPassword textbox. So the user could enter a password and click submit and the compare validator would not fire and the page would submit.

So I needed a RequiredFieldValidator on txtConfirmPassword but this is only needed to be enabled after some text is entered in the txtPassword text box.

I found this article:
http://www.aspdotnetfaq.com/Faq/How-to-control-ASP-NET-Validator-Controls-Client-Side-validation-from-JavaScript.aspx

and implemented this javascript. Note I am using a little jQuery to get the controls. (1.4.1)

And using this information was able to write the following script:

<script type="text/javascript">
    $(document).ready(function() {
        $('#<%=txtPassword.ClientID %>').change(function() {
            var value = $('#<%=txtPassword.ClientID %>').val();
            if(value.length > 0){
                EnableValidators(true);
            } else {
                EnableValidators(false);
            }
        });
    });

    function EnableValidators(enable)
    {
        ValidatorEnable(document.getElementById('<%=rfvConfirmPassword.ClientID%>'), enable);
    }
</script>

The interesting thing is “ValidatorEnable” is a Asp.Net function that client-side enables and disables the validators.

Nice :-)

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
Categories: ASP .Net, c# Tags:
  1. No comments yet.
  1. No trackbacks yet.