Reputation: 4028
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?
Upvotes: 4
Views: 917
Reputation: 100175
Should be:
//add slashes and remove quotes
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 ]*$/;
Upvotes: 3
Reputation: 2650
try
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 ]*$/;
Upvotes: 2
Reputation: 119837
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 ]*$/;
Upvotes: 4
Reputation: 14875
"^[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.
Upvotes: 3