Regular Expression:
- Regular expression is a set of characters called Pattern.
- These Patterns are used to search required information from the given text.
- JavaScript providing RegExp object with Properties and Functions.
Some of the Regular Expressions for Alphabets and Numerical Validation
[abc] – find any character in the brackets a, b or c [a-z] – find characters a to z lowercase. [0-9] – Find all digits [^xyz] – find any character other than specified in the brackets. [^abc] Find any character NOT between the brackets [^0-9] Find any character NOT between the brackets (any non-digit) (word) – find the “word” specified in the round brackets [abc|xyz] – find either the characters a,b,c or x,y,z |
Non-Empty Text Field validation: In the program, we are not using any regular expression. We check the length of input to specify Error message if the user not entered any value.
<html> <head> <script> function valid(){ var x = document.getElementById(‘val’).value; if(x.length == 0){ alert(“Please Enter Name”); document.getElementById(‘val’).focus(); return false; } return true; } </script> </head> <body> <form> Enter Name : <input type=’text’ id=’val’/> <input type=’button’ onclick=”valid()” value=’Submit’ /> </form> </body> </html> |
Program to Validate only Numerical input:
<html> <head> <script> function valid(){ var x = document.getElementById(‘val’).value; var expr = new RegExp(“^[0-9]”); if(expr.test(x)){ alert(“Thank you for your valid input”); } else{ alert(“Please eneter numbers only”); document.getElementById(‘val’).focus(); } } </script> </head> <body> <form> Enter Age : <input type=’text’ id=’val’/> <input type=’button’ onclick=”valid()” value=’Submit’ /> </form> </body> </html> |
Program to Validate only Alphabetical Input:
<!doctype html> <html> <head> <script> function valid(){ var x = document.getElementById(‘val’).value; var expr = new RegExp(“^[a-zA-Z]”); if(expr.test(x)){ alert(“Thank you for your valid input”); } else{ alert(“Name should not contain numbers”); document.getElementById(‘val’).focus(); } } </script> </head> <body> <form> Enter Name : <input type=’text’ id=’val’/> <input type=’button’ onclick=”valid()” value=’Submit’ /> </form> </body> </html> |