Compare Passwords in HTML5 form validation using Jquery

| By Webner

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 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 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 class="form-group">
<input type="submit" name="submitChangePassword" value="Submit" id="editSuperAdminPwd">

Screenshot is displayed below for above form:


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


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:

function checkPassword(){
if ($('#newPasswordAgain').val() !== $('#newPassword').val()) {
$('#newPasswordAgain')[0].setCustomValidity('Passwords must match.');

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:


Leave a Reply

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