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;
}