Skip to content

Instantly share code, notes, and snippets.

@angelikatyborska
Last active January 19, 2023 21:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelikatyborska/d6dc425700d9c0d53c5fd19ed1683e31 to your computer and use it in GitHub Desktop.
Save angelikatyborska/d6dc425700d9c0d53c5fd19ed1683e31 to your computer and use it in GitHub Desktop.
Providing custom error messages for built-in HTML5 form validation
<!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