Monday, October 09, 2006

Email Validation using RegExp in javascript

We will now see the simple Email Vaidation which we usually use in our projects:

The function explained below is applicable for sathyavathi123@blogspot.com

function validateMail()
{
var email = document.getElementById("TextBox2").value;
var emailRegEx = /^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{3,3}$/;
if(email != null)
{
if(!emailRegEx.test(email))
{
alert("Email is not in correct format.");
return false;
}
}

This method will be called on button click.

In this,
the variable email, holds the value in the textbox.
the emailRegEx describes the format for the email which is entered in the textbox.
/^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{3,3}$/;
Here ^ - starting position
$ - ending position
[a-zA-Z0-9]+ which implies in the example as Sathyavathi123 but the characters in the bracket must come 1 or more times.
.[a-zA-Z]{3,3} which means after . user can enter only 3 characters.

To check whether the entered string and the regexp has sink or not, we have two built in methods:
a) test - which returns boolean value.
b) match - which returns either 1 or 0.

Tuesday, October 03, 2006

Exclude special characters in atextbox using RegExp

For example,

There is a textbox controld(id:txtName) which accepts all values except special characters like @, #

for this the RegExp should be like this:

function ExcludeSpecialCharacter()
{
var a = documnet.getElementById('txtName').value;
var aRegEx = /^[^\@\#]$/;

if(a != null)
{
if(!aRegEx.test(a))
{
alert("Name does not accept special characters like @ #.");
return false;
}
}
}