Friday, November 23, 2012

Basic Regular Expression Patterns I

Here, I'll discuss on the usage of Regular Expressions in various validation checking. We are using Javascript Regular expression patterns. These patterns can be tested on any input end-user provides.

Example 1. Input NUMBER

Conditions :
1. The input number must be 8 digit long
2. It should start with '5', '6' or '9'

Code :
var pattern = /^[569]{1,1}[0-9]{7,7}$/  
var tel_no  = "56895869";  // User Input
pattern.test(tel_no);      // Will return true as Pattern is matching

Example 2. Input STRING

Conditions :
1. The input string should start with the letter 'T' in capital
2. The second letter is a vowel
3. Second letter is small case letter
4. The third letter is any small letter non-digit character
5. The whole string is a 3-letter word.


Code :
var pattern = /^T[aeiou][a-z]$/;

Example 3. Input STRING

Conditions :
1. The string should start with any non-digit character including underscore
2. The string can have only underscore as special character.
3. The string can have maximum 10 characters.

Code : 

var pattern = /^[^0-9_][0-9a-zA-Z_]{0,9}$/;

Example 4. Input STRING

Conditions :
1. The input string must have the word "Band"


Code :
var pattern = /\bBand\b/;

Discussions :: The '\b' modifier is used to find word boundaries. That means string like

"Band, great!!!"
"Test Band..."
"This is my Band. Great na?",
"Nice Band!!!"
"OK!!Band starts now"
"Good Band"

will test true against the pattern. This pattern matches for "Band" followed by a newline character, "Band" word followed by punctuation mark or any such mark followed by the word "Band" etc.

Strings like 

"Great Bands"
"Bands of Britain"

will always return false because "Band" has not appeared as a single word. Check next part of this article here.

No comments: