Written by:2009/04/20 08:06 AM
How many of you guys have web forms on your websites that require users to fill in. Part of those forms require information to be valid. Things like phone numbers, email addresses. Validating these form fields can be a task in and of itself. Many have always resorted to server side validation. But that requires a round trip to the server. Is there an easier way to do this? Can this be done on the client side, before they submit the web form to the server.
Well thankfully we have something called regexp, or Regular expression. A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *.txt to find all text files in a file manager. The regex equivalent is .*\.txt$.
Regular expressions are used by many text editors, utilities, and programming languages to search and manipulate text based on patterns. For example, we can use Regular Expression to check whether the user input is a valid ID number, a valid phone number or a valid password , etc. We can use this functionality to validate against email addresses filled on a web form. We want to make sure that our email field in our form complies to a valid email address. It must have an “@”, a period, a domain, etc.
I came across a nice little regular expression article that gives us a nice concise expression to use for email addresses. http://www.zparacha.com/ultimate-java-regular-expression-to-validate-email-address/ Although it is a website that deals primarily with Java, the regexp will work with any language that implements regular expression libraries.
The main regular expression looks like this:
Following email addresses will pass validation
On his site, Zaheer Paracha, explains a lot on the make up of this regular expression. You can find it on his blog about Java Regex Validation. But I am going to post an insert here from that particular post. Make sure you read it to get the full gist of the regexp explanation.
Email format: A valid email address will have the following format:
There are so many rules and implementations of regexp that it is out of the scope of this post to deal with them all. But below you will find some links to other websites that will explain and give you a lot more information and examples
0 comment(s) so far...
Do you want to receive blog updates via e-mail. Then just click on the link below. You will be redirected to Google's feed burner, where you can fill out a form. Supplying your e-mail address.
The subscription is managed entirely by Google's Feedburner. We cannot and do not collect your email address.
Subscribe to The Brave Programmer by Email
Sign up with Disqus to enjoy a surprise box of features