Monday, October 01, 2012

Javascript Date Validation check

Suppose you have a contact form on your website, which job hunters will fill up during Job application. In that form, they must fill up the DOB text input.

We need to check ::

1. Date given is in correct format :: dd-mm-yyyy is maintained
2. Date is actually a correct data, date such as '29-02-1978' will be discared

We take the following actions for the points above respectively::

1. We use a regular expression to check the formatting of the date
2. We use Javascript Date() function feature for achieving the correct date

Check the code below, we have written a function called date_validation() which takes a date and returns true if it is a valid date, returns false otherwise.

<script type="text/javascript">
function date_validation(user_date)
{
// Use a RegEX pattern to check formatting
var patt = /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4,4}$/;

// If the input string's format is okay
if( patt.test(user_date) )
{

// Extract Day Month Year from user input
var p = user_date.split(/-/);
var a_year  = p[2];
var a_month = p[1];
var a_day   = p[0];


// Create a new Date Object with each part
// Date() object does not hold original data
// if the Date is wrong
var t_d = new Date(a_year, a_month - 1, a_day);

// Now check
if( t_d.getDate() == a_day && t_d.getMonth() == (a_month - 1) && t_d.getFullYear() == a_year )
{
   // Date is Okay
   return true;
}
else
{
   return false;
}
}
}

console.log( date_validation("29-2-1978") ); // False

console.log( date_validation("29-2-1976") ); // True
</script>

The code above is quite self-explanatory. Still, let's discuss some parts of it.


1.  We used a RegEX pattern to validate the user input. So the patt.test() returns true if the input is as per our expectation.

2. Next we extract date, month and year info from the user input by calling a split function. Split accepts Regular Expression as its arguments. So the pattern /-/ means we wanted to split it by the character hyphen (-). After the split, each part is stored in an array.

3. Next we create a Date object with these date, month and year information. In Javascript, month starts from 0, hence to mean February (month : 2), we need to use 1 (2-1).  

For example, if we want to create a date object with date : 29-2-1978, we need to provide

// January is 0, Feb is 1 etc
var test_date = new Date(1978, 1, 29); 

Javascript Date() function has a feature, if we want to create a Date object with an invalid date, it changes to a different valid date. For example, the above line will generate an object with date "1-3-1978" as "29-2-1978" does not exist on calendar. But if we used a valid date, the object gets created with that valid date only.

So, with the following lines ::

if( t_d.getDate() == a_day && t_d.getMonth() == (a_month - 1) && t_d.getFullYear() == a_year )

... we just checked whether the entered date is changing or not, if changes, it means that entered date is invalid. So, if the date is valid, this function returns true and false in other cases.

Check out some other validation techniques using Javascript in articles Email Validation in JavascriptNumeric Data validation using Javascript

To know basic Javascript Regular Expression Patterns, see Article Basic Regular Expression Patterns I 

No comments: