Friday, January 27, 2012

JS Regex

JavaScript has a good way to do RegExp or (regular expression) that's used to validate input data fields in a web form at the client side.In this post i will show how to validate a string input that doesn't start with a digit.

Initially define the required pattern
var pattern=new RegExp(patternStr,modifiers);
Or simply:
var pattern= /<patternStr>/<modifiers>

Modifiers are optional and can be at least one of the following:
  • i to enforce case-insensitive characters.
  • g to enforce global searching/matching if there're multiple occurrence
Also you can use these methods to search/match required pattern in strings:

stringObj.match(pattern); //returns null or the pattern matches.

pattern.test(stringObj); //returns true if the pattern is found or false otherwise.
pattern.exec(stringObj); //returns null or the pattern matches.

Example:


<script type="text/javascript">

var pattern= /^\d/; //without double or single quotes

var inputString1="31userName";
var inputString2="userName123";
document.write(pattern.test(inputString1)); //result is true
document.write(pattern.test(inputString2)); //result is false

</script>

No comments:

Post a Comment