Home > Enterprise >  Why do I see an input validation error even if the value is correct?
Why do I see an input validation error even if the value is correct?

Time:01-16

I'm very much a beginner, but I notice a weird behavior on the simple input validation.

If I enter a user name that respects requirements, e.g., "PaulMinami," with the first attempt, everything is OK, and the form submits. If my first attempt is incorrect, let's say it's just one letter, the problem occurs during subsequent attempts. If I enter a username that respects the rules right after the unsuccessful attempt, I still can't pass validation and submit a form.

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="practice.css">
    <title>Learning inputs</title>
  </head>

  <body>
    <h1>Form validation</h1>
    <section >
      <form action="https://api.sheetmonkey.io/form/57kwXg5yDU1wz5rtHjRLAm" method="POST">
        <section >
          <label for="username">Username</label><br>
          <input 
          type="text" 
          name="username" 
          id="username"
          placeholder="Create unique username"
          pattern="[A-Za-z]{6,12}" 
          required 
          oninvalid="this.setCustomValidity('Username must contain only letters, and length has to be between 6 and 12 character')" 
          ><br>
        </section>

        <button type="submit">Submit</button>
        
      </form>
    </section>
  </body>

</html>

CodePudding user response:

I think when an input field is triggered as invalid input, setCustomValidity(‘….’) will be fired and show the custom message. After correcting the value of the input, the result of validation is still an error.


    <section >
        <label for="username">Username</label><br>
        <input 
          type="text" 
          name="username" 
          id="username"
          placeholder="Create unique username"
          pattern="[A-Za-z]{6,12}" 
          required 
          oninvalid="this.setCustomValidity('Username must contain only letters, and length has to be between 6 and 12 character')" 
          oninput="this.setCustomValidity('')"
          ><br>
    </section>

oninput="setCustomValidity('')" is used to clear the result after each input.

  • Related