Form Validation Functions with Regular Expressions

Contact Us or call 1-877-932-8228
Form Validation Functions with Regular Expressions

Form Validation Functions with Regular Expressions

Regular expressions can be used to write sophisticated form validation functions. For example, earlier in the course, we wrote a checkEmail() function that looked like this:

function checkEmail($email)
{
	$email = trim($email);
	if (!checkLength($email,6))
	{
		return false;
	}
	elseif (!strpos($email,'@'))
	{
		return false;
	}
	elseif (!strpos($email,'.'))
	{
		return false;
	}
	elseif (strrpos($email,'.') < strpos($email,'@'))
	{
		return false;
	}
	return true;
}

We can use a regular expression to make this function both simpler and more powerful:

function checkEmail($email)
{
	$emailPattern = '/^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/';
	return preg_match($emailPattern,$email));
}

A nice thing about this is that we can use virtually the same function to do client-side validation with JavaScript:

function checkEmail(EMAIL)
{
	var reEmail = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;
	return reEmail.test(EMAIL));
}

So, by using regular expressions in this way, you make it easy to create a similar function library on the client side.

Next