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:
[js]
<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>
[/js]
The interesting thing is “ValidatorEnable” is a Asp.Net function that client-side enables and disables the validators.

Nice 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.