30 December 2010

Client side validation: Using Regular expression in Java-script

Some sample regular expressions:

1. FQDN (Fully qualified domain name):

2. IP- Address:

3. IP address with subnet mask ( form:

4. Email address:

5. Word:

How to use regular expression in Java script:
Create Regex object:
var regxpVal =  new RegExp("REGULAR-Expression");

Validate Value:
if (! regxpVal.test("value to test")) {
   alert("Invalid Value provided");

var fqdnRegex = new RegExp("^[a-z0-9-_]+(\\.[a-z0-9-_]+)*\\.([a-z]{2,4})$");

if (! fqdnRegex.test("google.com")) {
  alert("google.com is not valid fqdn");

alert("google.com is valid fqdn");

1 comment:

  1. Your regex for FQDN's accepts a FQDN where one of the labels starts or ends with a hyphen, for example '-google.com' or 'google-.com' which are not valid FQDN's. (See section 2.3.1 of http://tools.ietf.org/html/rfc1035 ) Also if you are not going to change your regular expression at runtime it's faster to use the // notation for example: var fqdnRegex = new /^[a-z0-9-_]+(\\.[a-z0-9-_]+)*\\.([a-z]{2,4})$/; ( see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions )