1

I have some javascript code that is trying to verify if the input of a text input box matches the format of US postal codes. There's a div block below the input box that will either contain "This is an invalid US postal code" in red or the opposite message in green, and the div block becomes visible as soon as some input is made. However, for any and all gibberish I enter into the box, I keep getting the green message (valid postal code) instead of the red error message.

I've tried 2 different regex codes for the format test. Both cases gave the same result.

Here is the HTML and Javascript code:

<p>What is the postal code?</p><br>
                <input type="text" name="zipcode" oninput="return validate_zip()"><br>
                <div id="zipcode_error" class="error_verify" style="color:red">This is required</div><br>
                <script>
                    var zip = document.getElementsByName("zipcode")[0];
                    function validateZip(val) {
                        var re = /^[0-9]{5}(?:-[0-9]{4})?$/;
                        console.log(re.test(val))
                        return re.test(val);
                    }
                    function validate_zip() {
                        document.getElementById("zipcode_format_error").style.visibility = "visible";
                        document.getElementById("zipcode_format_error").style.height = "auto";
                        if (validateZip(zip)) {
                            document.getElementById("zipcode_format_error").innerText = "This is an invalid format for US postal codes";
                            document.getElementById("zipcode_format_error").style.color = "red";
                        }
                        else {
                            document.getElementById("zipcode_format_error").innerText = "This is a valid format";
                            document.getElementById("zipcode_format_error").style.color = "green";
                        }
                    }
                </script>
                <div id="zipcode_format_error" class="error_verify"></div><br>

Here is the CSS:

.error_verify {
    visibility: hidden;
    height:0;
}
Luv Tomar
  • 127
  • 2
  • 13
  • 1
    Your `if ()` logic is backwards. The regex `.test()` function returns `true` when the regular expression matches, and `false` when it doesn't. – Pointy Jul 26 '19 at 15:13
  • I'm such an idiot. Thanks. – Luv Tomar Jul 26 '19 at 15:17
  • 3
    I would just use a public api for this. I don't see much value in a regex here as they could give you a valid regex, but the zip code could very well still be invalid: https://stackoverflow.com/questions/7129313/zip-code-lookup-api – mwilson Jul 26 '19 at 15:24
  • I'll look into it. Thanks. – Luv Tomar Jul 26 '19 at 15:33

0 Answers0