I am calling the following JS to validate a UK postal code:
<script type="text/javascript">
function jsre(theField) {
var chk_postalcode = "^[A-Z0-9 ]*[A-Z][A-Z0-9 ]*\d[A-Z0-9 ]*$|^[A-Z0-9 ]*\d[A-Z0-9 ]*[A-Z][A-Z0-9 ]*$";
var txtpostalcode = document.getElementById("txtPostCode");
if (!chk_postalcode.test(txtpostalcode.value)) {
alert("Valid");
} else {
alert("Invalid");
}
}
</script>
<asp:TextBox ID="txtPostCode" runat="server" onchange="jsre(this);"></asp:TextBox>
I get the runtime error as:
Error: Object doesn't support property or method 'test'
I took the help from http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html to frame my code.
Can anyone help me how can i make the code working?
chk_postalcode
is still a string
so it has no test()
method.
turn it into a RegExp object:
var chk_postalcode = /^[A-Z0-9 ]*[A-Z][A-Z0-9 ]*\d[A-Z0-9 ]*$|^[A-Z0-9 ]*\d[A-Z0-9 ]*[A-Z][A-Z0-9 ]*$/;
"^[A-Z0-9 ][A-Z][A-Z0-9 ]\d[A-Z0-9 ]$|^[A-Z0-9 ]\d[A-Z0-9 ][A-Z][A-Z0-9 ]$"
change it to /^[A-Z0-9 ][A-Z][A-Z0-9 ]\d[A-Z0-9 ]$|^[A-Z0-9 ]\d[A-Z0-9 ][A-Z][A-Z0-9 ]$/
. Remove double quotes and put slash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With