Regular Expressions plays a very important role while writing code in JavaScript, below example shows how we can validate a 5 digit number.
Recently when I was working on my private projects, through JavaScript I need to validate a form where in which user needs to enter only 5 digit number in a input box. For this task we will be writing 2 or 3 lines of code in JavaScript, in JavaScript we can make use of Regular Expressions and for the above task the code will be reduced to only 1line instead of writing 2 or 3 lines of code. Isn't it interesting... Wow Right!
Below is the Example:
<script language="javascript">
function validatePostalCode(){
var fivedigitnumber=/^\d{5}$/ //regular expression defining a 5 digit number
if (document.getElementById('postalinput').value.search(fivedigitnumber)==-1) //if failed, caution the user
{
alert("Please enter a valid 5 digit number")
}
else
{
alert("Hurray!!!"); // if success
}
}
</script>
<!-- form -->
<form name="postalcodeform">
<input type="text" name="postalinput" size=15 id="postalinput">
<input type="button" onClick="validatePostalCode()" value="Validate & Go">
</form>
Description of the code:
var fivedigitnumber=/^\d{5}$/
- ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning.
- \d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters.
- $ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string.
Above one is the simple code which will give JavaScript developers an idea how Regular Expressions will act while writing JavaScript code. Using Regular Expressions we can also built complex expressions that validate virtually anything we want.
0 comments:
Post a Comment