Regular Expressions in JavaScript
With the help of Regular Expressions we can make our own patterns for validation and validate form as per our requirement. This post will describe how you can make your own regular expression in JavaScript.
Above is the syntax how to define the expression in JavaScript.
Between /^ $/ we have to write our expression as below.
<head>
<script>
function validate() {
var name = document.getElementById(‘txtVal’).value;
var exp = /^abc$/;
if(!name.match(exp)) {
alert(‘Invalid Value’);
return false;
} else {
alert(‘Submited’);
return true;
}
}
</script>
</head>
<body>
<form method=”POST”>
Enter Name : <input type=”text” id=”txtVal”/> <br/>
<input type=”submit” value=”Submit” id=”btnSubmit” onclick=”return validate()”/>
</form>
</body>
</html>
Description : In the above example we have written “abc” in expression, so only if we will enter “abc” in textbox then it match with expression and return true and form will submit on the server otherwise not.
Likewise below are the some basis and important patterns.
In this expression we have written “+” in front of a, so we have to enter “a” at least one time in textbox and we can write more than ones also.
Note : “+” is for one or more than one number of repetition.
In this expression we have written “*” in front of b, so we can enter “b” 0 or any time in textbox.
Note : “*” for Zero or any number of repetition.
In this expression we have written ”?” in front of b, so we can enter “b” 0 or One time only in textbox.
Note : “?” for Zero or One number of repetition.
Note : [ ] for Group. We can enter one small alphabet only in above expression.
Some Other Patterns :
/^[a-zA-Z0-9]*$/ | Alpha Numeric Values only, “*” for Zero or any number of expressions. |
/^\w$/ | Alpha Numeric Value only. |
/^\W*$/ | Alpha numeric values not allowed. Allow Special characters only. “*” for any number of expressions. |
/^\d$/ | Decimal value only. |
/^\D*$/ | Decimals not allowed. “*” for any number of expressions. |
/^\d{3}$/ | Exactly 3 numbers of decimals allowed only. Note : {} are used for specific numbers of decimals, characters or special symbols. We can use two parameters {minNumbers, maxNumbers} |
/^ $/ | blank space to allow space. |
/^\w+\@\w+\.\w+$/ | Regular Expression for email id. |