Regular Expressions

Regular Expressions give you more power to validate strings in a script. With regular expressions you can create a pattern of what a valid value can be and test what was entered against it. For instance, you want to find out if a required field has data in it. Previous examples have shown how to check for an empty string or a space. However if two spaces were entered, the field would be valid. Look at the following pattern /^[ ]*$/.

function isValidField(FirstName){
	var chkName = /^[ ]*$/; 
	if (chkName.test(FirstName)){
		alert("First Name cannot be blank");
		return false;
	}
	else
		return true;
}		
Click here to see the demo.

You want to find out if a valid email address has been entered. A normal email address has a combination of at least 3 characters and/or numbers before and after the "@" sign, followed by a ".". JavaScript string methods could be used to parse the information before and after the "@" and before the ".". This could be quite cumbersome.

/^[A-Za-z0-9]{2,}@[A-Za-z0-9_]{3,}\.[A-Za-z]{2}/ Look at the pattern to validate an email address.

Click here to see the demo.

Validate a phone number (999) 999-9999. /(^[1-9][0-9]{2})([1-9][0-9]{2})([0-9]{4}$)/

Click here to see the demo.

Remove Carriage Return and Line feed characters from a textarea. /\r\n/g

Click here to see the demo.

Validate a phrase for alphanumeric characters (from the book). /[^a-z\d ]/i

Click here to see the demo.

Modify the demo to remove the not '!'
Click here to see the demo.