4

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?

4 Answers 4

4

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 ]*$/;
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

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 ]*$/;

Comments

2

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 ]*$/;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.