Useful Javascript Field Validation using Regular Expressions
March 8th, 2008 Posted in Javascript
We always need to validate all the fields that the user enters in the forms , and I think the easiest way to validate it is by Javascript and the use of Regular expressions.
In this post we are going to set a few example of how to validate a Date, Currency, Number, Url, Email, Phone number and others.
So now lets go to the examples.
Validate a Date
function isDate(date)
{
var MonthDays = Array();
MonthDays[0] = 31;
MonthDays[1] = 0;
MonthDays[2] = 31;
MonthDays[3] = 30;
MonthDays[4] = 31;
MonthDays[5] = 30;
MonthDays[6] = 31;
MonthDays[7] = 31;
MonthDays[8] = 30;
MonthDays[9] = 31;
MonthDays[10] = 30;
MonthDays[11] = 31;
var daysInMonth;
var aData = date.split(’/');
if (aData.length != 3)
return false;
var monthSelected = parseInt(aData[0], 10);
var daySelected = parseInt(aData[1], 10);
var yearSelected = parseInt(aData[2], 10);
if (isNaN(daySelected) || isNaN(monthSelected) || isNaN(yearSelected))
return false;
if (monthSelected == 2)
daysInMonth = (((yearSelected % 4 == 0) && ((!(yearSelected % 100 == 0)) || (yearSelected % 400 == 0))) ? 29 : 28 );
else
daysInMonth = MonthDays[monthSelected - 1];
if (daySelected < 1 || daySelected > daysInMonth)
return false;
if (monthSelected < 1 || monthSelected > 12)
return false;
if (yearSelected < 1)
return false;
return true;
}
Validate an Integer or Number
function isInteger(value)
{
var re = /^\-?[0-9]+$/;
return re.test(value);
}
Validate an Email
function isEMail(value)
{
var exp_email1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
var exp_email2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
return !exp_email1.test(value) && exp_email2.test(value);
}
Validate a Currency
function isCurrency(value)
{
var re = /^[0-9]+(\.[0-9]{2})?$/;
return re.test(value);
}
Validate an Url
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
Validate a Phone Number
function isPhoneNumber(value)
{
var regexp = /^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/;
return regexp.test(value);
}
Validate a Year
function isYear(value)
{
var exp_year = /^[0-9]{4}$/;
return exp_year.test(value);
}
I hope that you’ll find these examples useful and if you have any question , please fill free to ask me anything.
See you in my next post