Skip to content

Instantly share code, notes, and snippets.

@dexygen
Last active January 27, 2019 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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</label><input id="zip" maxlength="5" /></div>
<div id="zip-error" style="color: red"></div>
<div><label>Click to "blur" zip field</label><input type="checkbox" /></div>
<script>
const zip = document.getElementById('zip');
const zipErrEl = document.getElementById('zip-error');
const errorMsg = "Please enter 5 digits, optionally followed by a dash and 4 digits";
const keyupRegex = new RegExp("^\\d{0,5}$");
const blurRegex = new RegExp("^\\d{5}$");
function validateZip(regex) {
if (regex.test(this.value)) {
zipErrEl.innerHTML = '';
}
else {
zipErrEl.innerHTML = errorMsg;
}
}
zip.focus();
zip.addEventListener('keyup', function() {
validateZip.call(this, keyupRegex);
});
zip.addEventListener('blur', function() {
validateZip.call(this, blurRegex);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment