Minimal Password Match Validation Plugin with jQuery

File Size: 3.48 KB
Views Total: 6084
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Minimal Password Match Validation Plugin with jQuery

An extremely lightweight jQuery plugin designed for user signup form that displays a validation hint if the "Confirm Password" doesn't matches the "Password" field while the user it typing. Also has an ability to restrict the minimum length of the password to 8 digits.

How to use it:

1. Create an user register form as follow.

<form action="#" method="post">
  <p>
    <label for="username">Username</label>
    <input id="username" name="username" type="text">
  </p>
  <p>
    <label for="password">Password</label>
    <input id="password" name="password" type="password">
    <span>Enter a password longer than 8 characters</span> </p>
  <p>
    <label for="confirm_password">Confirm Password</label>
    <input id="confirm_password" name="confirm_password" type="password">
    <span>Please confirm your password</span> </p>
  <p>
    <input type="submit" value="SUBMIT" id="submit">
  </p>
</form>

2. Load the needed jQuery JavaScript Library at the end of the document.

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 

3. The core jQuery script to validate the password filed.

var $password = $("#password");
var $confirmPassword = $("#confirm_password");
var $userName = $("#username");

//Hide Hints

$("form span").hide();

function isPasswordValid() {
return $password.val().length > 8;
}
function isUsernameValid() {
 return $userName.val().length;
}

function arePasswordsMatching () {
 return $password.val() === $confirmPassword.val();   
}

function canSubmit() {
 return isPasswordValid() && arePasswordsMatching() && isUsernameValid();   
}

function passwordEvent() {

  //Find out if password is valid.   
    if(isPasswordValid()) {
    
    //Hide Hint if valid.
    $password.next().hide();
   } else {
   
    //Else show hint
   $password.next().show();
  }    
}

  //Find out if password and confirmation match.
function confirmPasswordEvent() {
    if(arePasswordsMatching()) {
   
         //Hide hint if matched.
        $confirmPassword.next().hide();

      //Else show hint.
    } else { 
        $confirmPassword.next().show();
        
    } 
}

function enableSubmitEvent(){
    $("#submit").prop("disabled", !canSubmit());
}

//When event happens on password input
$password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent);

//When event happens on confirmation input
$confirmPassword.focus(confirmPasswordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent);

// Call Function
enableSubmitEvent();

This awesome jQuery plugin is developed by manetsberger90. For more Advanced Usages, please check the demo page or visit the official website.