I'm sure most of you from the programming world are familiar with regular expressions. For most of you that are from the programming world and aren't familiar with them - you should be ashamed of yourselves.
I'm only this haughty because I only figured out how to use regular expressions LAST NIGHT. Can you believe that? In the middle of a large project where the deadline looms among the next sunrise and validation on a HUGE form is key, I learned to master the use of ye ole RegEx... But not without a large amount of help, though.
I really have to give credit to the guys over at GSkinner.com for their RegExr tool. With this tool, I was able to turn my email address validation code from this :
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}
return true
}
function ValidateForm(){
var emailID=document.frmSample.txtEmail
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
To this :
function validateEmail(str) {
var RE_EMAIL = /^[a-z]+[\w-_]+@[a-z]+\.[^@]*\w\w$/
if(RE_EMAIL.test(str)) {
return true;
}
else {
return false;
}
}
If you are like me and you never understood regular expressions, I would advise you give them a try. If you're a web developer, one of these days you are going to have to develop a form component that needs validation. Learning regular expressions is a definite time saver and I would suggest you invest the necessary time into learning them.