Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.