Themeforest

Form Validation Using jQuery and Regular Expressions

Regular expressions offer an extremely flexible and powerful way of adding validation to your website forms. Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements.

In this post I have included several example regular expressions that we have used in our web design projects for validating form input.

For this tutorial we assume you know how to create the HTML form and add jQuery to your site. For samples you can refer to previous posts – check passwords using jQuery, email validation using jQuery or view the demo form.

View Demo

For each example we have created a css class, which can then be assigned to the relevant form element. If you are creating your own validation code/plugin there are obviously more efficient ways of creating a complete validation system but for the tutorial we have kept each regular expression sample separate and also use the “keyup” event.

jQuery To Handle the Submit Button

In order to use these validation functions in a form we need to add jQuery that will check for the presence of any span elements with the class “error”. We do this by using the length property. If the length is > 0 the form submit can be stopped and the user alerted:

$('#btn-submit').click(function() {
  if($('span.error').length > 0){
    alert('Errors!');
    return false;
  } else {
    $('#btn-submit').after('<span class="error">Form Accepted.</span>');
    return false;
  }
});

Now that we have this code to check for errors, we can add any of the examples below to the form.

Example 1 – Validates Numeric Characters Only

Accepts only 0 – 9

$('.keyup-numeric').keyup(function() {
    $('span.error-keyup-1').hide();
    var inputVal = $(this).val();
    var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
    if(!numericReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-1">Numeric characters only.</span>');
    }
});

Example 2 – No Special Characters

Allows only letters, numbers and spaces. All other characters will return an error.

$('.keyup-characters').keyup(function() {
    $('span.error-keyup-2').remove();
    var inputVal = $(this).val();
    var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-2">No special characters allowed.</span>');
    }
});

Example 3 – Maximum of 8 Characters

Allows all characters up to a maximum of 8. Useful for passwords, etc. The value can easily be increased/descreased by changing the {0,8}

$('.keyup-limit-8').keyup(function() {
    $('span.error-keyup-3').remove();
    var inputVal = $(this).val();
    var characterReg = /^([a-zA-Z0-9]{0,8})$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-3">Maximum 8 characters.</span>');
    }
});

Example 4 – US Phone Number

Allows numbers 2-9 for the first and second group of 3 followed by 0-9 for the last 4 with the groups separated by “-” e.g:

  • 234-234-1234 = OK
  • 134-234-1234 = Error
  • 234-134-1234 = Error
$('.keyup-phone').keyup(function() {
    $('span.error-keyup-4').remove();
    var inputVal = $(this).val();
    var characterReg = /^[2-9]\d{2}-\d{3}-\d{4}$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-4">Format xxx-xxx-xxxx</span>');
    }
});

Example 5 – Validate Date Format

Allows date format – mm/dd/yyyy – including “/”. All other combinations will return errors e.g:

  • 01/31/2001 = OK
  • 31/01/2001 = Error
  • 1/01/2001 = Error
$('.keyup-date').keyup(function() {
    $('span.error-keyup-5').remove();
    var inputVal = $(this).val();
    var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
    if(!dateReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-5">Invalid date format.</span>');
    }
});

Example 6 – Check For Possible Fake Text

This is an interesting example, which checks for possible fake text being entered into your form. The regex looks for groups of the same letters occuring in groups of 3 or more e.g:

  • foo = OK
  • fff = Error
$('.keyup-fake').keyup(function() {
    $('span.error-keyup-6').remove();
    var inputVal = $(this).val();
    var fakeReg = /(.)\1{2,}/;
    if(fakeReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-6">Invalid text.</span>');
    }
});

Example 7 – Check Email Address Format

This is a standard regular expression, which is used to validate email addresses to ensure they follow the standard format:

  • email@email.com = OK
  • email.email.com = Error
$('.keyup-email').keyup(function() {
    $('span.error-keyup-7').remove();
    var inputVal = $(this).val();
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-7">Invalid Email Format.</span>');
    }
});

Example 8 – No Free Email Addresses

Another useful email validation regular expression checks for email addresses using free emails – in the example below we check for yahoo, gmail and hotmail:

  • email@yahoo.com = Error
  • email@email.com = OK
$('.keyup-email-2').keyup(function() {
    $('span.error-keyup-8').remove();
    var inputVal = $(this).val();
    var emailFreeReg= /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!aol.com)([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailFreeReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-8">No Free Email Addresses.</span>');
    }
});

Example 9 – Visa Card Number Format

For an example of validating a credit card we can use the following regular expression, which checks the input against the standard format for Visa credit cards – All card numbers must start with a 4 & cards may either have 16 digits or 13 digits for older cards:

  • 4166000000000000 = OK
  • 4166000000000 = OK
  • 41660000000000001 = Error
  • 2166000000000000 = Error
$('.keyup-cc').keyup(function() {
    $('span.error-keyup-9').remove();
    var inputVal = $(this).val();
    var ccReg = /^4[0-9]{12}(?:[0-9]{3})?$/;
    if(!ccReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-9">Invalid visa card number</span>');
    }
});

Hopefully some of the above examples will be useful for your forms and also help demonstrate how powerful regular expressions can be.

View Demo

4 Comments

  • Thanks for the great Tutorial on jQuery and regex… Great Help..

    • Glad you found it useful

  • Hello,

    I’m using WordPress 3.1.2 with a variety of forms plugins, but none let me do client-side validation and conditional branching to form sections using client-side javascript. Most want to do the validation on the server-side with PHP.

    I’d like to use JQUERY’s REGEX capabilities to a) validate that a zipcode field is 5-digits and, if that’s true to b) test that zipcode for a match against three different arrays of zipcode-city pairs.

    If a match is found in a particular array, the form is routed to a particular form section with the appropriate geographic pricing. If no match found, an error or exception message is generated.

    Do you have or can you direct me to any examples of client-side javascript for testing and conditional branching within forms?

    many thanks in advance!

    • Hi Tom,

      I have uploaded a demo page, which hopefully covers your requirements – http://www.designchemical.com/lab/jquery/demo/jquery_conditional_validation.htm. If the zipcode is present in one of the arrays the relevant text input will slide down.

      Im sure there is a cleaner way of handling the different arrays though but the concept works …

      The original validation and form submit is based on our last tutorial – jQuery Animated Error Messages & Form Validation

      Regex for checking 5 digit zipcode – /^\d{5}$|^\d{5}-\d{4}$/

      So the complete validation for the zipcode input is:

      // Declare arrays
      var arr1 = ['A', '10100', 'B', '10200', 'C', '10300'];
      var arr2 = ['D', '20100', 'E', '20200', 'F', '20300'];
      var arr3 = ['G', '30100', 'H', '30200', 'I', '30300'];
      
      var zipReg = /^\d{5}$|^\d{5}-\d{4}$/;
      if($(this).hasClass('zipcode') == true){
      
          if(!zipReg.test(inputVal)){
      
              // If fail regex check
              $parentTag.addClass('error').append($error.clone().text('Enter valid zipcode'));
      
          } else {
      
              // Check array 1
              if (jQuery.inArray(inputVal, arr1) > 0){
      
                  // Present in 1st array - add function
                  $('#response-1').slideDown();
      
              // Check array 2
              } else if (jQuery.inArray(inputVal, arr2) > 0){
      
                  // Present in 2nd array - add function
                  $('#response-2').slideDown();
      
              // Check array 3
              } else if (jQuery.inArray(inputVal, arr3) > 0){
      
                  // Present in 3rd array - add function
                  $('#response-3').slideDown();
      
              } else {
      
                  // Not present in any array display error message
                  $parentTag.addClass('error').append($error.clone().text('No Match'));
      
              }
          }
      }