HTML5 default validation for confirm password

In this section, we am going to see how you we easily validating HTML5 default validation for confirm the password. Generally in HTML5 when we create a form we simply write “required” attribute to the form element and it starts validating itself without other javascript code. But for confirm password validation we would required to add few lines of code that will set the validation in the default way.

HTML

1
2
3
4
5
6
7
8
9
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
        <input id="password" placeholder="Password" required="" type="password">
        <input id="confirm_password" placeholder="Confirm Password" required="" type="password">
 
        <button class="pure-button pure-button-primary" type="submit">Confirm</button>
    </fieldset>
</form>

JAVASCRIPT

1
2
3
4
5
6
7
8
9
10
11
12
13
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
 
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
 
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

6 comments: