Compare Passwords in HTML5 form validation using Jquery

Author - Ishpreet Kaur

In one of our projects, requirement was to compare two password values using HTML5 form validation (display the message in the same format as regular HTML5 messages are displayed).

Let us assume that we have a HTML5 form for change password screen:

<form action=”Controller/User.php”
<div class="form-group">
<label for="newPassword">New Password *</label>
<input type="password" name="newPassword" id="newPassword" class="form-control" placeholder="New Password"  pattern="(?=.*\d)(?=.*[A-Z])(?=.*[~`!@#$%^&*()\-_+={};:\[\]\?\.\\/,]).{6,}" title="Password must contain a capital letter,  a special character and a digit. Password length must be minimum 6 characters."  autocomplete="off" required onchange="checkPassword()" >
</div>
<div class="form-group">
<label for="retypeNewPassword">Retype New Password *</label>
<input type="password" name="newPasswordAgain" id="newPasswordAgain" class="form-control" placeholder="New Password"  onkeyup="checkPassword()"  title="Passwords must match"  autocomplete="off" required>
</div>                            
<div class="form-group">
<p style="color:blue; text-align:left;">Note: Password must contain a capital letter, a special character and a digit. Password length must be minimum 6 characters.</p>
</div>
<div class="form-group">
<input type="submit" name="submitChangePassword" value="Submit" id="editSuperAdminPwd">
</div>
</form>

Screenshot is displayed below for above form:

1

If we do not follow the required pattern for the password we see this type of error message due to HTML5 validation rules:

2

Similarly, we want that Retype New Password field should also display HTML5 error message if someone does not enter same password as entered in the New Password Field.

Lot of examples/links provide solution for this situation by using javascript’s setCustomValidity() function, but not using jQuery. Let us see how we can display HTML5 error message with setCustomValidity() function in jQuery:

<script>
function checkPassword(){
if ($('#newPasswordAgain').val() !== $('#newPassword').val()) {
$('#newPasswordAgain')[0].setCustomValidity('Passwords must match.');
}
else{
$('#newPasswordAgain')[0].setCustomValidity('');
}
}
</script>

We have provided jQuery function checkPassword() on keyup event to Retype New Password Field. With above method, the HTML5 error message is displayed when Retype New Password Field value is not same as New Password Field. See the following screenshot:

3

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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