Javascript validation of Email Address, Numeric Values and an Input Mask for Numbers Only
Feb.05, 2008 in
Development
A couple of very simple yet handy routines for validation of form fields:
Function to validate an email address (see original post):
function ValidateEmail(email){
var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
var regex = new RegExp(emailReg);
return regex.test(email);
}
Function to validate a number:
function ValidateNumber(num)
{
return num.match(/^\d+$/);
}
Input mask for a field to only accept numbers:
In your html add the following:
<input name="numericfld"
onkeypress="return(ForceNumbersOnly(this, event));"
onchange="RemoveNonNumeric(this)" />
Then implement the following functions:
function ForceNumbersOnly(myfield, e, dec)
{
var key;
var keychar;
if (window.event)
{
key = window.event.keyCode;
}
else if (e)
{
key = e.which;
}
else
{
return true;
}
if(key != 46 && key != 45 && key > 31 && (key < 48 || key > 57))
{
return false;
}
else
{
return true;
}
}
function RemoveNonNumeric(myfield)
{
var re = /[^0-9\.\-]/g;
if(re.test(myfield.value))
{
myfield.value = myfield.value.replace(re, '');
myfield.value = myfield.value.replace(/\./, '');
}
}
Tags: javascript, validation

April 16th, 2010 at 9:43 pm
Wow, this works perfectly, thanks a lot dude, you saved me some working hours!
June 29th, 2010 at 6:16 am
This is really great and much useful