Answer the question
In order to leave comments, you need to log in
How to optimize form validation?
Hello, I have a small form and I need to display an alert in case it is filled incorrectly.
I do it with
<form action="">
<input type="text" required>
<input type="text" required id="test">
<button type="submit" onclick="submitForm()">send</button>
</form>
<script>
function submitForm() {
if (!document.querySelector('form').checkValidity()) {
alert("invalid field");
} else {
alert("valid fields");
}
}
</script>
<form action="">
<input type="text" required value="123">
<input type="text" required id="test" value="123">
<button type="submit" onclick="submitForm()">send</button>
</form>
<script>
function submitForm() {
if (!document.querySelector('form').checkValidity()) {
alert("invalid field");
} else {
alert("valid fields");
}
document.getElementById("test").value = "";
}
</script>
Answer the question
In order to leave comments, you need to log in
You don't need JS to validate the form. Use the pattern attribute for fields:
https://webdesign.tutsplus.com/en/tutorials/html5-...
you need to bind the submit event of the form, not the click of the button
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question