Last active
January 19, 2023 21:52
-
-
Save angelikatyborska/d6dc425700d9c0d53c5fd19ed1683e31 to your computer and use it in GitHub Desktop.
Providing custom error messages for built-in HTML5 form validation
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> | |
<title>Form Validation</title> | |
<style> | |
body { padding: 10px; } | |
</style> | |
</head> | |
<body> | |
<form> | |
<label for="name">Name</label> | |
<input type="text" id="name" name="name" required /> | |
<button type="submit">Submit</button> | |
</form> | |
<script> | |
const input = document.querySelector('input[name="name"]'); | |
input.addEventListener('invalid', function (event) { | |
if (event.target.validity.valueMissing) { | |
event.target.setCustomValidity('Please tell us how we should address you.'); | |
} | |
}) | |
input.addEventListener('change', function (event) { | |
event.target.setCustomValidity(''); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment