jquery form validation

jQuery form validation is another useful technique that you can use to validate form data and instruct the user to fill in required data in proper format. Rather than informing the user that the data being sent are not in proper format after the form is processed, it is always a better idea to alert the user before the form is submitted.

We can use events like keyup, keydown, keypress, keyrelease, focus, focusout, change, etc, before the submit button is clicked, so that, the user instantly gets the idea that the form data is not qualified to be processed.

Lets have a look at the sign up form used here for demonstration.

Register

<h3>Register</h3>
<form id="register">
  <div class="form-group">
    <label>Username <span class="error usernameError"></span></label>
    <input type="text" name="username" id="username" class="form-control">
  </div>
  <div class="form-group">
    <label>Email <span class="error emailError"></span></label>
    <input type="text" name="email" id="email" class="form-control">
  </div>
  <div class="form-group">
    <label>Phone <span class="error phoneError"></span></label>
    <input type="text" name="phone" id="phone" class="form-control">
  </div>
  <div class="form-group">
    <label>Password <span class="error passwordError"></span></label>
    <div class="input-group">
      <input type="password" name="password" id="password" class="form-control">
      <span class="input-group-addon" id="viewpass"><i class="glyphicon glyphicon-eye-close"></i></span>
    </div>
  </div>
  <div class="form-group">
    <label>Confirm Password <span class="error cpasswordError"></span></label>
    <div class="input-group">
      <input type="password" name="cpassword" id="cpassword" class="form-control">
      <span class="input-group-addon" id="viewcpass"><i class="glyphicon glyphicon-eye-close"></i></span>
    </div>
  </div>
  <div class="form-group">
    <button class="btn btn-success" id="submit">Sign Up</button>
  </div>
</form>	

Here, we added error class to each input field where we will be showing error related to that field in case there is any error.

Lets set some errors by default on the form, so that, the form won't submit unless it meets the criteria we define.

<script>
$('#submit').click(function(){
  usernameError = true;
  emailError = true;
  phoneError = true;
  passwordError = true;
  cpasswordError = true;
})
</script>

Here, we have set some error values as true that should change if proper data is added in related field. Next, we stop the script from running if any of those values is still true.

<script>
$('#submit').click(function(){
  usernameError = true;
  emailError = true;
  phoneError = true;
  passwordError = true;
  cpasswordError = true;
  if(usernameError == true || emailError == true || phoneError == true || passwordError == true ||cpasswordError == true){
    return false;
  }else{
  	$('#register').submit();
  } 
})
</script>

Now, we need some methods to check each of those form fields and determine whether the error values should remain true or false.

<script>
$('#submit').click(function(){
  usernameError = true;
  emailError = true;
  phoneError = true;
  passwordError = true;
  cpasswordError = true;
  checkUsername();
  checkEmail();
  checkPhone();
  checkPassword();
  checkCpassword();
  if(usernameError == true || emailError == true || phoneError == true || passwordError == true ||cpasswordError == true){
    return false;
  }else{
  	$('#register').submit();
  } 
})
</script>

Now, we will need to define each of those functions individually and check related field values. Keep in mind, these functions must be defined outside the submit click event script.

Check Username

Checking a username is quite easy. All you have to do is get the value of the username field. If it is empty or below the length you define, you show error message and set the error value to true. If the criteria is met, you will remove the error and set the error value to false.

function checkUsername(){
  var username = $('#username').val();
  if(username.length == 0){
    usernameError = true;
    $('.usernameError').html("Username is required *");
  }else{
    if(username.length < 3){
      usernameError = true;
      $('.usernameError').html("Username must not be less than 3 characters *");
    }else{
      usernameError = false;
      $('.usernameError').empty();
    }
  }
}	

Check Email

Checking email will also be quite similar to checking username except the fact that we have defined the input type as text. We can change it to email, but, people with slight knowledge of html can modify it to text before sending data and thus, increase the chance of spam. So, its always a better idea to define the field as text and check the email format using jQuery. All you need to do is add a regex that defines the email pattern and match it with the data being sent via that field.

function checkEmail(){
  var email = $('#email').val();
  if(email.length == 0){
    emailError = true;
    $('.emailError').html("Email is required *");
  }else{
    var pattern = /^\w{2,}([\.-]?\w+)*@\w{2,}([\.-]?\w+)*.(\w{2,3})+$/g;
    if(!pattern.test(email)){
      emailError = true;
      $('.emailError').html("Invalid email address *");
    }else{
      emailError = false;
      $('.emailError').empty();
    }
  }
}	

Learning regex is quite easy if you want to. If not, you can get email, phone and password regex all over inetrnet, you can pick one that satisfies you and use them in your script. Let's see what these regex symbols mean.

  • / / is the wrapper for the regex. Regex must be written inside these two slashes.
  • ^ defines the beginning of the regex.
  • \w matches any word character including alphabets, numbers, hyphens & underscores. Equivalent to [A-Za-z0-9_]
  • {2,} requires the character count before @ to be of minimumn 2 characters
  • () groups a set of regex
  • [\.-] allows adding dot and hyphen to the front part of an email
  • ? allows the user to choose either to add characters or not
  • ([\.]?\w) However, written together in a group means if the user adds dot or hyphen to the front part of the email, it can't be the last symbol before the @ symbol
  • + forces all following characters to match the defined regex
  • *@ prevents the regex written before @ to check characters after it appears in the value while making the value a must in the sequence
  • *. prevents the regex written before dot symbol to check characters after it appears in the value while making the value a must in the sequence
  • {2,3} requires the character count following dot to be of minimumn 2 characters and maximum 3 characters
  • $ symbolizes the end of regex
  • g retains the index of last match character and allow iterative search

pattern.test(email) will match the email value with the regex pattern. If the pattern matches the regex, true is returned and false is returned in another case. ! symbolizes not is programming language. Hence, if the pattern test is not true, error will be shown.

Check Phone

Now, the email regex is done, we can check the phone numbers in similar manner. In fact, phone field is added here to make your regex understanding much better. Writing up phone regex should be easy one. After all, we will need to accept only numbers and optionally a + sign at most.

Rather than writing up the regex like email, its much easier to write it the opposite way. We will define what won't be allowed in this pattern.

function checkPhone(){
  var phone = $('#phone').val();
  if(phone.length == 0){
    phoneError = true;
    $('.phoneError').html("Phone number is required *");
  }else{
    var regex = /[^0-9+ -]+/g;
    if(regex.test(phone)){
      phoneError = true;
      $('.phoneError').html("Invalid phone number *");
    }else{
      phoneError = false;
      $('.phoneError').empty();
    }
  }
}	

Here, the regex says anything beyond the numbers, space, plus and hyphen sign won't be accepted. [^] matches any character that is not inside the set. So, anything beyond the defined set would match the pattern. And, we will set the error to true if the match occurs in this case.

Check Password

For password regex, we wrote up the regex to make sure that the password contains at least and number, a special character, a capital letter and the length should be between 8 to 16 characters.

function checkPassword(){
  var password = $('#password').val();
  if(password.length == 0){
    passwordError = true;
    $('.passwordError').html("password is required *");
  }else{
    if(password.length < 8){
      passwordError = true;
      $('.passwordError').html("Password must be at least 8 characters long *");
    }else{
      var passReg = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{8,16}$/g;
      if(!password.match(passReg)){
        passwordError = true;
        $('.passwordError').html("Password must contain at least a number, a special character and a capital letter *");
      }else{
        passwordError = false;
        $('.passwordError').empty();
      }
    }		
  }
}
  • (?=.*[0-9]) requires at least one numeric value
  • (?=.*[!@#$%^&*]) requires at least one special character
  • (?=.*[A-Z]) requires at least one capital letter
  • [a-zA-Z0-9!@#$%^&*] defines the range of characters we can use
  • {8,16} defines the minimum and maximum length of the password

Check Confirm Password

Checking confirm password must be the easiest among all validations. All you need to do is compare it with password value and set the error true or false depending upon the match.

function checkCpassword(){
  var cpassword = $('#cpassword').val();
  var password = $('#password').val();
  if(cpassword != password){
    cpasswordError = true;
    $('.cpasswordError').html("Password and Confirm password do not match *");
  }else{
    cpasswordError = false;
    $('.cpasswordError').empty();
  }
}	

Now, after all the validation scripts are written, you might want to make those scripts run right after a user feeds on some value. For that, you can initiate the script whenever the focus is off from the input fields.

$('#username').focusout(function(){
  checkUsername();
})
$('#email').focusout(function(){
  checkEmail();
})
$('#phone').focusout(function(){
  checkPhone();
})
$('#password').focusout(function(){
  checkPassword();
})
$('#cpassword').focusout(function(){
  checkCpassword();
})	

Make sure the scripts are inside script tag but not inside the submit() function.

Now, all scripts are written, lets make it more interesting by adding script to show and hide the password. Since, we have already added the icons right beside the password fields, we can make them clickable and thus, toggle password on click.

<script>
$('#viewpass').click(function(){
  var password = $('#password')[0];
  if(password.type == 'password'){
    password.type = 'text';
    $(this).children('i').attr("class","glyphicon glyphicon-eye-open");
  }else{
    password.type = 'password'
    $(this).children('i').attr("class","glyphicon glyphicon-eye-close");
  }
})
$('#viewcpass').click(function(){
  var password = $('#cpassword')[0];
  if(password.type == 'password'){
    password.type = 'text';
    $(this).children('i').attr("class","glyphicon glyphicon-eye-open");
  }else{
    password.type = 'password'
    $(this).children('i').attr("class","glyphicon glyphicon-eye-close");
  }
})
</script>

Now, you can see the password and confirm password values by clicking on the eye. We even changed the icon class depending upon the input type.

Now onwards, if all criteria are met within the form, only then further processing will be executed.


0 Like 0 Dislike 0 Comment Share

Leave a comment