Ishan
Ishan

Reputation: 4028

Javascript runtime error:

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

Answers (4)

Sudhir Bastakoti
Sudhir Bastakoti

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

bkconrad
bkconrad

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

Joseph
Joseph

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

bhups
bhups

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

Related Questions