Skip to content

Instantly share code, notes, and snippets.

@dexygen
Last active January 27, 2019 01:27
Show Gist options
  • Save dexygen/b0225fffe4e6d3b39c088a72e431e0dd to your computer and use it in GitHub Desktop.
Save dexygen/b0225fffe4e6d3b39c088a72e431e0dd to your computer and use it in GitHub Desktop.
Validates while typing and onblur
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
label {
display: inline-block;
width: 160px;
}
</style>
</head>
<body>
<div><label>Zip (+4)</label><input id="zip-4" maxlength="10" /></div>
<div id="zip-4-error" style="color: red"></div>
<div><label>Click to "blur" zip field</label><input type="checkbox" /></div>
<script>
const zip = document.getElementById('zip-4');
const zipErrEl = document.getElementById('zip-4-error');
const errorMsg = "Please enter 5 digits, optionally followed by a dash and 4 digits";
const keyupRegex = new RegExp("^\\d{0,5}(-\\d{0,4})?$");
const blurRegex = new RegExp("^\\d{5}(-\\d{4})?$");
function validateZip4(regex) {
if (regex.test(this.value)) {
zipErrEl.innerHTML = '';
}
else {
zipErrEl.innerHTML = errorMsg;
}
}
zip.focus();
zip.addEventListener('keyup', function() {
validateZip4.call(this, keyupRegex);
});
zip.addEventListener('blur', function() {
validateZip4.call(this, blurRegex);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment