How to stop repeated HTML5 Constraint validation prompts?

Viewed 39

When using html5's constraint validation I get continuous prompts on every keypress.

    <div class="md-form mb-5">
        <input type="username" id="regUsername" name='username' class="form-control validate" 
               value = "<?php echo htmlspecialchars($firstName); ?>" required minlength="2" maxlength="30"/>
        <label data-error="wrong" data-success="right" for="regUsername">Your username</label>
        <span id='usernameStatus2'></span>

    </div>

I listen for focusout and check if username is available.

$("#regUsername").focusout(function (e) {
    var el = document.getElementById(e.target.id);
    if (!el.reportValidity()) {
        $(el).closest("input, textarea").removeClass('is-valid').addClass("is-invalid");
    } else {
        $(el).closest("input, textarea").removeClass('is-invalid').addClass("is-valid");
       checkAvailability();
    }

});

The issue I am having is after every keypress the validate prompt gets repeated. 1. user enters in-valid username and hits tab. 2. focusout function is called. 3. if valid according to html5's checkValidity(), call to my function checkAvailability(). 4. if not available, setCustomValidity() to error msg i.e. 'not available', checkValidity() called. 5. while focus is still on input, when user presses any key the custom validity msg prompts which creates confusion as the updated input value may be available despite the repeated prompts.

HTML5 validator will keep focus on in-valid input and repeat the in-valid prompt on every keypress, so if username 'testuser' is unavailable typing additional characters after 'testuser' like 'testuser2' will cause the in-valid prompt, when in fact 'testuser2' is available which is only known after an actual focusout event.

How do I stop these repeated prompts?

*edit- not as big of a deal, but also wondering why subsequent inputs trigger focusout when putting focus on next input using .focus() after passing validation. Unable to repeat with chrome debugger open because then it doesn't happen. I tried e.preventDefault() and e.stopPropagation() in focusout function.

0 Answers
Related