D
D
Dutymy2021-07-08 19:41:31
JavaScript
Dutymy, 2021-07-08 19:41:31

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>

However, I'm assuming that the form is validated on both checkValidity() and submit() - then it turns out that I'm checking it twice - first on the button and then on submit.
This hypothesis seems to confirm this code
<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>

where after the first form validation one field is emptied. Can I optimize my approach and only call validation once. For example, without checking the form when submitting it a second time?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2021-07-08
@zkrvndm

You don't need JS to validate the form. Use the pattern attribute for fields:
https://webdesign.tutsplus.com/en/tutorials/html5-...

A
Anton Shamanov, 2021-07-08
@SilenceOfWinter

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 question

Ask a Question

731 491 924 answers to any question