JavaScript Coder

JavaScript Form Validation - Confirm Password

javascript form validation confirm password password

Here is a quick JavaScript validation to check whether password and confirm password fields match.

The code below compares the field( password and confirm password) values and displays the error message when the passwords does not match.

Sample Javascript code for comparing password with confirm password

function validateForm(event) {
    var password = document.getElementById('myform_password').value;
    var conf_password = document.getElementById('myform_confirm_password').value;
    if (password && password !== conf_password) {
        document.getElementById('error_pswd_match').classList.remove('hidden');
    } else {
        document.getElementById('error_pswd_match').classList.add('hidden');
        alert("Validation Success!");
    }

    event.preventDefault();
}

The input fields have required attribute. Blank password will trigger error from the browser

<input type="password" id="myform_password" name="password" required />

See Also