The code for the alpha Numeric validation in javascript is below:
function alphanumericValidation(obj){
var i = 0;
var returnVal = true;
if(obj != null){
var val = new String(obj.value);
for(i = 0; i<val.length; i++){
var ch = val.charAt(i);
if((ch<'a' || ch>'z') && (ch<'A' || ch>'Z') && (ch<'0' || ch>'9')){
alert('Only alphanumeric characters are allowed in this field.');
obj.focus();
obj.select();
returnVal = false;
break;
}
}
if(returnVal){
return true;
}
else{
return false;
}
}
}
Code for DOB validation in JS in below:
// the format for DOB is yyyy-mm-dd
function dobValidation(dob){
var yearfield=dob.value.split("-")[0];
var monthfield=dob.value.split("-")[1];
var dayfield=dob.value.split("-")[2];
var mon = parseFloat(monthfield);
var returnval=false;
var date = dob.value;
if(date.length == 10){
if(date[4] == '-' && date[7] == '-'){
var dateOfBirth = new Date(yearfield,monthfield,dayfield);
var today = new Date();
var oneDay=1000*60*60*24;
var diff = Math.ceil((today.getTime() - dateOfBirth.getTime()) / oneDay);
if(diff <= 0){
alert('Birth date cannot be today or in future. Please enter again.');
returnval=false;
}
else{
var yearInt = parseFloat(yearfield);
var currYearInt = today.getFullYear();
var monthInt = parseFloat(monthfield);
var dayInt = parseFloat(dayfield);
if(monthInt >= 1 && monthInt <= 12){
if(dayInt>=1 && dayInt <= 31){
returnval=true;
}
else{
alert('Date cannot be greater than 31 or less than 1.');
returnval=false;
}
}
else{
alert('Month cannot be greater than 12 or less than 1.');
returnval=false;
}
}
}
else{
alert('Birth date format invalid. Please enter again in \'yyyy-mm-dd\' format. eg: \'1999-
01-01\'');
returnval=false;
}
}
else{
alert('Invalid birth date. Please enter again in \'yyyy-mm-dd\' format. eg: \'1999-01-01\'');
returnval=false;
}
if (returnval==false){
dob.select();
}
return returnval;
}
Code for email validation is below:
function emailValidate(text){ // text is the object which contains email value.
var str=text.value;
var returnVal = true;
if(str!=''){
var filter=/^([A-Za-z0-9_\-\.])+@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,3})$/
if (!filter.test(str)){
returnVal = false;
}
}
if(returnVal){
return true;
}
else{
text.focus();
text.select();
alert("Invalid Email Address. Valid Example:abc1@abc.com");
return false;
}
}
This is the code for String validation, only alphabets are allowed in the string.
function stringValidation(name){ // name is the object of the component which contains string.
var i = 0;
var returnVal = true;
if(name!=null){
var val = new String(name.value);
for(i = 0; i<val.length; i++){
var ch = val.charAt(i);
if((ch<'a' || ch>'z') && (ch<'A' || ch>'Z')){
alert('Only alphabets are allowed in this field.');
name.focus(); // this sets the focus to the field which contains the string.
name.select(); // this selects the string so that the user can change directly.
returnVal = false;
break;
}
}
if(returnVal){
return true;
}
else{
return false;
}
}
}