30 December 2010

Client side validation: Using Regular expression in Java-script

Some sample regular expressions:

1. FQDN (Fully qualified domain name):
^[a-z0-9-_]+(\.[a-z0-9-_]+)*\.([a-z]{2,4})$

2. IP- Address:
(((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))\\.){3}((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))

3. IP address with subnet mask (255.255.255.255/24) form:
^(((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))\\.){3}((25[0-5])|(2[0-4][0-9])|^([01]?[0-9][0-9]?))[/](([1-2]?[0-9])|([3][0-2]))$

4. Email address:
^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$

5. Word:
^\w+$


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");
}

Example:
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 )

    ReplyDelete