Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Validates while typing and onblur
<!doctype html>
<html lang="en">
<meta charset="utf-8">
label {
display: inline-block;
width: 160px;
<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>
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.addEventListener('keyup', function() {, keyupRegex);
zip.addEventListener('blur', function() {, blurRegex);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment