Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
Ishan Avatar asked Dec 16 '22 02:12

Ishan


2 Answers

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 ]*$/;
like image 73
Joseph Avatar answered Jan 05 '23 12:01

Joseph


"^[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.

like image 21
bhups Avatar answered Jan 05 '23 11:01

bhups