Created
November 22, 2017 06:54
-
-
Save simenbrekken/81966be65afd416f9de6ac847aaa7417 to your computer and use it in GitHub Desktop.
Field-error-handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(""); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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