Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created November 22, 2017 06:54
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 simenbrekken/81966be65afd416f9de6ac847aaa7417 to your computer and use it in GitHub Desktop.
Save simenbrekken/81966be65afd416f9de6ac847aaa7417 to your computer and use it in GitHub Desktop.
Field-error-handling
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<!-- Styles -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="root">
<form>
<label for="firstName">First Name:
<input id="firstName" name=firstName type="text" required>
</label>
<label for="lastName">Last Name:
<input id="lastName" name=lastName type="text" required>
</label>
<label for="phone">Phone:
<input id="phone" name=phone type="tel" pattern="^\d{8}$" required>
</label>
<label for="news">Receive newsletter?
<input id="news" name=news type="checkbox">
</label>
<button id="submit">Save changes</button>
</form>
</div>
<!-- Scripts -->
<script src="index.js"></script>
</body>
</html>
const allInput = document.querySelectorAll("input:not(#news)");
allInput.forEach((input, i) => {
input.addEventListener("invalid", event => {
if ((input.name == "firstName") && (input.validity.valueMissing)) {
input.setCustomValidity("Missing first name!");
}
else if ((input.name == "lastName") && (input.validity.valueMissing)) {
input.setCustomValidity("Missing last name!");
}
else if ((input.name == "phone") && (input.validity.valueMissing)) {
input.setCustomValidity("Missing phone number!");
}
else if ((input.name == "phone") && (input.validity.patternMismatch)) {
input.setCustomValidity("Phone number must be 8 digits");
} else {
input.setCustomValidity("");
}
});
});
body {
font-family: Menlo;
}
label {
display: block;
line-height: 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment