Last active
August 6, 2020 15:25
-
-
Save angelikatyborska/741362771032bd460e9336585fe3f34b to your computer and use it in GitHub Desktop.
Custom validation messages - 3 inputs
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 charset="UTF-8"> | |
<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 /> | |
<label for="email">Email</label> | |
<input type="email" id="email" name="email" required /> | |
<label for="phone">Phone Number</label> | |
<input type="tel" id="phone" name="phone" required pattern="$\+[0-9]" /> | |
<button type="submit">Submit</button> | |
</form> | |
<script> | |
const nameInput = document.querySelector('input[name="name"]'); | |
const emailInput = document.querySelector('input[name="email"]'); | |
const phoneInput = document.querySelector('input[name="phone"]'); | |
const allInputs = [nameInput, emailInput, phoneInput]; | |
nameInput.addEventListener('invalid', function (event) { | |
if (event.target.validity.valueMissing) { | |
event.target.setCustomValidity('Please tell us how we should address you.'); | |
} | |
}) | |
emailInput.addEventListener('invalid', function (event) { | |
if (event.target.validity.valueMissing) { | |
event.target.setCustomValidity('We need your email address to send you an order conformation.'); | |
} | |
}) | |
phoneInput.addEventListener('invalid', function (event) { | |
if (event.target.validity.valueMissing) { | |
event.target.setCustomValidity('We need your phone number so that we can pass it on to the delivery company.'); | |
} | |
if (event.target.validity.patternMismatch) { | |
event.target.setCustomValidity('Your phone number should start with a + and a country code.'); | |
} | |
}) | |
allInputs.forEach(function (input) { | |
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