You are on page 1of 20

Document

Version

Modification Comments

Modified
By

Reviewed
By

Date

Draft 1.0

Created the document

Sunil Soni

11-09-2011

Comments

Contents
1.

Introduction......................................................................................................................................... 3

It is often a good idea to put your common JavaScript validation functions into a common file, so you
can include the file from all pages which need the form validation. ........................................................... 3
2.

3.

Date Validation .................................................................................................................................... 3


2.1.

FromDate toDate......................................................................................................................... 3

2.2.

IsDate 1:....................................................................................................................................... 4

2.3.

Aalternative 2: ............................................................................................................................. 5

2.4.

futureDateValidation :date format is DD/MM/YYYY .................................................................. 6

Email Validaton: ................................................................................................................................ 10


3.1.

JavaScript Code1 ....................................................................................................................... 10

Page 1

3.2.
4.

JavaScript Code 2....................................................................................................................... 11

Radio Button Validation .................................................................................................................... 12


4.1.

getCheckedValue(): ................................................................................................................... 12

4.2.

setCheckedValue():.................................................................................................................... 13

4.3.

isCheckedRadio: ........................................................................................................................ 13

5.

Checking for all Numbers: ................................................................................................................. 14

6.

Checking for all Letters: ..................................................................................................................... 15

7.

Checking for all Numbers and Letters: .............................................................................................. 16

8.

Restricting the Length: ...................................................................................................................... 16


Example: ................................................................................................................................................ 16

9.

Remove Special Characters from string: ........................................................................................... 17

10.

Username Validation: .................................................................................................................... 17

10.1. ....................................................................................................................................................... 17
11.

Password Validation: .................................................................................................................... 18

12.

Phone Number Validation: ........................................................................................................... 19

12.1.

Validation 1: .......................................................................................................................... 19

12.2.

Validation 2: .......................................................................................................................... 19

13.

Dropdown Validation: .................................................................................................................. 20

14.

Links: .............................................................................................................................................. 20

Dynamic JavaScript Form Validation ......................................................................................................... 20

Page 2

1. Introduction
It is often a good idea to put your common JavaScript validation functions into a
common file, so you can include the file from all pages which need the form
validation

2. Date Validation
2.1.

FromDate toDate
This is the code for date comparison fromDate should be less than toDate
var objFromDate = document.getElementById("fromdate").value;
var objToDate = document.getElementById("todate").value;
var FromDate = new Date(objFromDate);
var ToDate = new Date(objToDate);
var valCurDate = new Date();
val CurDate = valCurDate.getMonth()+1 + "/" + valCurDate.getDate() + "/" + valCurDate.getYear();
var CurDate = new Date(valCurDate);
if(FromDate > ToDate)
{
alert(fromname + " should be less than " + toname);
return false;
}
else if(FromDate > CurDate)
{
alert("From date should be less than current date");
return false;
}
else if(ToDate > CurDate)

Page 3

{
alert("To date should be less than current date");
return false;
}

2.2.

IsDate 1:
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strMonth=dtStr.substring(0,pos1)
var strDay=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1)
strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : mm/dd/yyyy")
return false
}

Page 4

if (strMonth.length<1 || month<1 || month>12){


alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 &&
day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and
"+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr,
dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}

2.3.

Aalternative 2:
function isDate(value)
{
var dateRegEx = new
RegExp(/^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,39]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[19]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[19]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-

Page 5

)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]
|[2468][048]|[13579][26]))$/);
if (dateRegEx.test(value))
{
return true;
}
return false;
}

2.4.

futureDateValidation :date format is DD/MM/YYYY

future date validation


function futureDateValidation(){
var dtCh="/";

// Get today's date and time...


var todaysDateTime = new Date();

// Parse off the time...


var monthValue = todaysDateTime.getMonth() + 1;
var dayValue = todaysDateTime.getDate();
var yearValue = todaysDateTime.getFullYear();
var todaysDate = new Date(Date.parse(monthValue + '/' + dayValue + '/' + yearValue));

// Create the FromDate to validate...


var enqiryFromDate = document.getElementById('fromDate').value; // this is how the date
looks like: ex 05/19/2008

var pos1=enqiryFromDate.indexOf(dtCh)

Page 6

var pos2=enqiryFromDate.indexOf(dtCh,pos1+1)
var strDay=enqiryFromDate.substring(0,pos1)
var strMonth=enqiryFromDate.substring(pos1+1,pos2)
var strYear=enqiryFromDate.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
var enqiryFromDateObj = new Date(Date.parse(month + '/' + day + '/' + year));

// Create the Todate to validate...


var enqiryToDate = document.getElementById('toDate').value;
var position1=enqiryToDate.indexOf(dtCh)
var position2=enqiryToDate.indexOf(dtCh,position1+1)
var stringDay=enqiryToDate.substring(0,position1)
var stringMonth=enqiryToDate.substring(position1+1,position2)
var stringYear=enqiryToDate.substring(position2+1)
//strYr=strYear
if (stringDay.charAt(0)=="0" && stringDay.length>1) stringDay=stringDay.substring(1)

Page 7

if (stringMonth.charAt(0)=="0" && stringMonth.length>1)


stringMonth=stringMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (stringYear.charAt(0)=="0" && stringYear.length>1)
stringYear=stringYear.substring(1)
}
toMonth=parseInt(stringMonth)
toDay=parseInt(stringDay)
toYear=parseInt(stringYear)
var enqiryToDateObj = new Date(Date.parse(toMonth + '/' + toDay + '/' + toYear));

if ( enqiryFromDateObj > todaysDate )


{
alert("Invalid date range!\nPlease choose a date that is not earlier than today!")

document.getElementById('fromDate').style.border = "2px solid red";


document.getElementById('fromDate').focus();
return false;
}
else
{
if(enqiryToDateObj > todaysDate){
alert("Invalid date range!\nPlease choose a date that is not earlier than
today!")
document.getElementById('toDate').style.border = "2px solid red";
document.getElementById('toDate').focus();

Page 8

return false;
}
else{
//alert('OK');
return true;
}
}
}

Page 9

3. Email Validaton:
Every email is made up for 5 parts:
1.
2.
3.
4.
5.

A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores


The at symbol @
A combination of letters, numbers, hyphens, and/or periods
A period
The top level domain (com, net, org, us, gov, ...)

Valid Examples:

bobby.jo@filltank.net
jack+jill@hill.com
the-stand@steven.king.com

Invalid Examples:

@deleted.net - no characters before the @


free!dom@bravehe.art - invalid character !
shoes@need_shining.com - underscores are not allowed in the domain name

3.1.

JavaScript Code1
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z09]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

Example:
<script type='text/javascript'>
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();

Page 10

return false;
}
}
</script>
<form>
Email: <input type='text' id='emailer'/>
<input type='button'
onclick="emailValidator1(document.getElementById('emailer'), 'Not a
Valid Email')"
value='Check Field' />
</form>

3.2.

JavaScript Code 2

function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value);
field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

// value of

if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) {
//test email
for illegal characters
fld.style.background = 'Yellow';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Yellow';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}

Page 11

4. Radio Button Validation


To make sure that a radio button has been chosen from a selection, we run through the array of
radio buttons and count the number that have been checked. Rather than sending the whole
radio object to a subfunction, which can be problematic (because the radio object has no
property indicating which value has been chosen), we pre-process the radio form element in a
for loop and send that result to a subfunction for evaluation.

4.1.

getCheckedValue():

return the value of the radio button that is checked return an empty string if none are checked, or
there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}

Page 12

4.2.

setCheckedValue():

set the radio button with the given value as being checked , do nothing if there are no radio buttons
if the given value does not exist, all the radio buttons are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}

4.3.

isCheckedRadio:

function isCheckedRadio(){
var isSelected=false;

Page 13

if( document.getElementById('tranType1').checked){
isSelected=true;
}
if( document.getElementById('tranType2').checked){
isSelected=true;
}

return isSelected;
}

5. Checking for all Numbers:


If someone is entering a credit card, phone number, zip code, similar
information you want to be able to ensure that the input is all numbers. The
quickest way to check if an input's string value is all numbers is to use a
regular expression /^[0-9]+$/ that will only match if the string is all numbers
and is at least one character long.
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
Example:
<script type='text/javascript'>
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){

Page 14

return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button'
onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only
Please')"
value='Check Field' />
</form>

6. Checking for all Letters:


This function will be identical to isNumeric except for the change to the regular expression
we use inside the match function. Instead of checking for numbers we will want to check for
all letters.
If we wanted to see if a string contained only letters we need to specify an expression that
allows for both lowercase and uppercase letters: /^[a-zA-Z]+$/ .
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

Example:
<script type='text/javascript'>
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;

Page 15

}
}
</script>
<form>
Letters Only: <input type='text' id='letters'/>
<input type='button'
onclick="isAlphabet(document.getElementById('letters'), 'Letters Only
Please')"
value='Check Field' />
</form>

7. Checking for all Numbers and Letters:

By combining both the isAlphabet and isNumeric functions into one we can check to see if a text input
contains only letters and numbers.
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

8. Restricting the Length:


Being able to restrict the number of characters a user can enter into a field is one of the best ways to
prevent bad data. For example, if you know that the zip code field should only be 5 numbers you know
that 2 numbers is not sufficient.
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ "
characters");
elem.focus();
return false;
}
}

Example:
<script type='text/javascript'>

Page 16

function lengthRestriction(elem, min, max){


var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ "
characters");
elem.focus();
return false;
}
}
</script>
<form>
Username(6-8 characters): <input type='text' id='restrict'/>
<input type='button'
onclick="lengthRestriction(document.getElementById('restrict'), 6,
8)"
value='Check Field' />
</form>

9. Remove Special Characters from string:


function clearText() {
document.formname.fieldname.value=filterNum(document.formname.fieldname.value
)
function filterNum(str) {
re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
}

10. Username Validation:


10.1.
function checkUsername (strng) {
var error = "";
if (strng == "") {
error = "You didn't enter a username.\n";
}
if ((strng.length < 4) || (strng.length > 10)) {
error = "The username is the wrong length.\n";

Page 17

}
var illegalChars = /\W/;
// allow only letters, numbers, and underscores
if (illegalChars.test(strng)) {
error = "The username contains illegal characters.\n";
}

10.2 UserId
Supports alphabets and numbers no special characters except underscore('_') min 3 and max 20
characters.
var ck_username = /^[A-Za-z0-9_]{3,20}$/;

11. Password Validation:


For the password field, we want to constrain the well keep it between 6 and 8 characters, and
we want to allow only letters and numbers no underscores . So we have to use a regular
expression to define which characters were banning. This one, includes \W everything but
letters, numbers, and underscores but we also need to explicitly mention underscores, so as
to permit only letters and numbers. Hence: /[\W_]/.
function checkPassword (strng) {
var error = "";
if (strng == "") {
error = "You didn't enter a password.\n";
}
var illegalChars = /[\W_]/; // allow only letters and numbers
if ((strng.length < 6) || (strng.length > 8)) {
error = "The password is the wrong length.\n";
}
else if (illegalChars.test(strng)) {
error = "The password contains illegal characters.\n";
}
else if (!((strng.search(/[a-z]+/) > -1)
&& (strng.search(/[A-Z]+/) > -1)
&& (strng.search(/[0-9]+/) > -1))) {
error = "The password must contain at least one
uppercase letter, one lowercase letter,
and one numeral.\n";
}

Page 18

12. Phone Number Validation:


To validate a phone number, first we want to clear out any spacer characters, such as
parentheses, dashes, spaces, and dots. We can do this with a regular expression and the
replace() method, replacing anything that matches our regular expression with a null string.
Having done that, we look at what we have left with the isNaN() function (which checks to see
if a given input is Not A Number), to test if it's an integer or not. If it contains anything other
than digits, we reject it.

12.1.

Validation 1:

var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');


//strip out acceptable non-numeric characters
if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.";
}

Then we count the length of the number. It should have exactly ten digits any more or
less, and we reject it.
if (!(stripped.length == 10)) {
error = "The phone number is the wrong length.
Make sure you included an area code.\n";
}

12.2.

Validation 2:

function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. Make sure you included an area code.\n";
fld.style.background = 'Yellow';
}
return error

Page 19

13. Dropdown Validation:


We want to make sure that the user has selected an option from our drop-down menu (and not
the first option, which isnt an option at all, but just a "Choose one" header). For this, we use the
select objects selectedIndex property, which returns the index of the selected option. If the
index is 0, we reject the input.
function checkDropdown(choice) {
var error = "";
if (choice == 0) {
error = "You didn't choose an option
from the drop-down list.\n";
}
return error;
}

14. Links:

Dynamic JavaScript Form Validation


http://sandbox.scriptiny.com/messages/messages.html
http://www.scriptiny.com/2008/04/dynamic-inline-javascript-form-validation/

Page 20

You might also like