I’ve the JavaScript code to validate a Zip code field in my page and that is as follows:
<script type="text/javascript">
var zip=$("#zip").val();
if (zip == '') {
errorMessage = REG_FIELD_EMPTY_ZIP;
$('#msg_zip').html(errorMessage).show();
}
else {
if ((zip.length) < 5)
{
errorMessage = REG_FIELD_LENGTH_ZIP;
$('#msg_zip').html(errorMessage).show();
}
else
{
if (!reg.test(zip)) {
errorMessage = REG_FIELD_ONLYDIGITS_ZIP;
$('#msg_zip').html(errorMessage).show();
}
else {
$('#msg_zip').html('').hide();
}
}
}
</script>
Here, i want to add some more conditions as:
1> this zip code field should also support Canadian Zip-code format (A#A #A#) with or without space it should accept. If the value is not in the Canadian Zip-code format,
2> It should accept only 5 digits.
How can i modify the above script so that i can make my zip code field to accept canadian zip-code format as well.
By searching i’ve found some regular-expression to accept canadian zip-code as /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$/; But when i tested it, it is not accepting the small case letters.
Can anyone clarify how to change my script so that it should accept the canadian-zip code or to accept only 5 digits. Thanks in Advance.
The regex you have for canadian zip-code is correct. If you want it to accept small case letters, you have to use it with case-insensitive option(i):
Regex for 5 digits:
Combining these two: