Thursday, August 28, 2008

Common Phone validator RegEx , E-mail validator Regular Expression

I use custom validators to validate my forms email and phone numbers.
In most of the public website that I developed I use this two common javascript functions to work with ASP.NET validators.






<asp:textbox id="txtPhoneNumber" maxlength="13" runat="server"></asp:textbox>

<asp:customvalidator id="valPhone" runat="server" cssclass="ErrorLabel" errormessage="* required" clientvalidationfunction="validatePhone" controltovalidate="txtPhoneNumber" validateemptytext="true"></asp:customvalidator>

function validatePhone(sender, args)
{
if(args.Value.length > 0)
{
var ex = /\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var re = new RegExp(ex);

if(re.exec(args.Value))
{
args.IsValid = true;
}
else
{
sender.errormessage= "* invalid";
sender.innerHTML= sender.errormessage;
args.IsValid = false;
}
}
else
{
sender.errormessage= "* required";
sender.innerHTML= sender.errormessage;
args.IsValid = false;
}
}

function validateEmail(sender, args)
{
if(args.Value.length > 0)
{
var ex = /^([a-zA-Z0-9_.+-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var re = new RegExp(ex );

if(re.exec(args.Value))
{
args.IsValid = true;
}
else
{
sender.errormessage= "* invalid";
sender.innerHTML= sender.errormessage;
args.IsValid = false;
}
}
else
{
sender.errormessage= "* required";
sender.innerHTML= sender.errormessage;
args.IsValid = false;
}
}


No comments:

Post a Comment