
javascript regex validate Special character

<html>
<head>
<title>Zip Code validation using regex</title>
<script type="text/javascript">
function validate() {
var zip = document.getElementById("zip").value;
var pattern = /^\d{5}([\-]\d{4})?$/;
if (pattern.test(zip)) {
alert("Your Zip Code : "+zip);
return true;
}
alert("It is not valid zip code !");
return false;
}
</script>
</head>
<body>
<h2>Validating Zip Code..</h2>
Enter Zip Code :
<input type="text" name="zip" id="zip" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

The above example validate 5 digit (eg-12344) or 5 digit-4 digit (eg- 12345-2323) zip code by using regular expression- /^\d{5}([-]\d{4})?$/ Here /../(forward slashes) is used to quote your regular expression. ^ shows beginning of string. \d{5} is for any digit 0-9 having 5 places. () is used for grouping content. [-] is used to put -.
\d{4} having sequence of digits of 4 places.
$ is used for ending the string.
Test() method takes one argument and check that to the pattern
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.