Monday, 26 May 2014

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 jQueryemail validation using jQueryor view the demo form.
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:
?
1
2
3
4
5
6
7
8
9
$('#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
?
1
2
3
4
5
6
7
8
$('.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.
?
1
2
3
4
5
6
7
8
$('.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}
?
1
2
3
4
5
6
7
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
?
1
2
3
4
5
6
7
8
$('.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
?
1
2
3
4
5
6
7
8
$('.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
?
1
2
3
4
5
6
7
8
$('.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
?
1
2
3
4
5
6
7
8
$('.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
?
1
2
3
4
5
6
7
8
$('.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
?
1
2
3
4
5
6
7
8
$('.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.

No comments:

Post a Comment