Wednesday, December 01, 2010

Javascript Form Validation

I used to do a script for every input to check their validity even to just check if it is blank.

The following is an easier and more streamline way of doing the same thing.

function isEmpty(query,query2){
if (query.value=="")
return query2+" must not be empty\n"
else
return ""
}
function isEmail(query,query2){
var emailRegEx = /^([a-z0-9][a-z0-9_.-]*[a-z0-9])+@+([a-z0-9][a-z0-9-]*[.])+[a-z0-9]{2,4}$/i;
if (emailRegEx.test(query.value)== false)
return query2+ " is not valid Email\n"
else
return ""
}
function isNumber(query,query2){
var numRegEx = /(^[+-]?[0-9]+\.[0-9]{1,}$)|(^[+-]?[0-9]+$)/;
if (numRegEx.test(query.value)== false )
return query2+ " is not valid Number\n"
else
return ""
}
function isInteger(query,query2){
var numRegEx = /^[+-]?[0-9]+$/;
if (numRegEx.test(query.value)== false)
return query2+ " is not valid Integer\n"
else
return ""
}
function isPlusNumber(query,query2){
var numRegEx = /(^[+]?[0-9]+\.[0-9]+$)|(^[+]?[0-9]+$)/;
if (numRegEx.test(query.value)== false)
return query2+ " is not Positive Number\n"
else
return ""
}
function isRadio(query,query2){
var testrad=false
for (radb=0;radb<query.length;radb++){
if (query[radb].checked == true)
testrad=true
}
if (testrad)
return ""
else
return query2 +" no selection\n"
}
function isSelect(query,query2){
// provided selected item 0 =not valid selection.
if (query.selectedIndex == 0)
return query2 +" no selection\n"
else
return ""
}
function isCheckBox(query,query2){
if (query.checked==true)
return ""
else
return query2+" must be checked\n"
}
function isPhone(query,query2){
// for Singapore only
var numRegEx = /(^[689]{1}[0-9]{7}$)|(^\+65[689]{1}[0-9]{7}$)/;
if (numRegEx.test(query.value)== false )
return query2+ " is not valid Phone Number\n"
else
return ""
}
function chksmt(){
obj=document.noname
ecode=""
ecode +=isEmpty(obj.Adr,"Address")
ecode +=isPlusNumber(obj.Pcode,"Postal Code")
ecode +=isInteger(obj.Cno,"Contact No")
ecode +=isEmail(obj.Email,"Email")
if (ecode !=""){
alert(ecode)
return 0
}
obj.submit()
}

No comments:

Post a Comment