below is a snippet of code I'm having issues with. I'm new to JS but the idea was to validate against input entered into a form. I got everything fine but eventually wanted to introduce the idea that the message for tooShort (if < 2 characters are entered) only appears after 2.5s so it doesn't appear at the start of when a user is typing input.
The current bug seems to be this:
- I enter "a" , which yields the "Too short" custom validity message after 2.5 seconds correctly
- Next I concatenate a "!" onto the input, so the forms current input is "a!" which immediately fires off the warning about pattern mismatch
- Next I delete the "!" from the input, so the form input just has the value "a" again
Heres where I'm confused, Immediately the default validation message for .tooShort quickly appears saying " Please lengthen this text to 2 characters or more (you are currently on using 1 character). "
Then after about 2.5 seconds it gets replaced by the custom message associated with tooShort inside of the timer etc.
I'm very confused on whats causing that default validation message to first appear and would love some insight so I can learn more!
let name = document.getElementById("visitor-name");
name.addEventListener("input", checkName);
let timer;
function checkName() {
let nameValidity = name.validity;
name.setCustomValidity("");
errorStyling(false);
clearTimeout(timer);
let shouldValidate = true;
let tooShortTimer = function() {
timer = setTimeout(dealWithError, 2500)
function dealWithError() {
{
name.setCustomValidity("Too short");
name.reportValidity();
errorStyling(true);
return;
}
}
}
if (nameValidity.patternMismatch) {
errorMessage = "Please use only letters";
name.setCustomValidity("Please use only letters");
errorInfo.innerHTML = "Letters only!"
regexError = true;
} else if (nameValidity.tooShort) {
shouldValidate = false;
tooShortTimer();
}
if (shouldValidate && name.checkValidity() === false) {
console.log(shouldValidate);
name.reportValidity();
errorObj = {
errorField: "name",
error: errorMessage,
input: name.value
};
form_errors.push(errorObj);
errorStyling(true);
}
function errorStyling(hasError, noError) {
if (hasError) {
name.style.backgroundColor = "red";
error.classList.add("error-message");
errorInfo.classList.add("error-message");
error.innerHTML = "Name Issue";
name.classList.add("InvalidCharacterFlash");
} else {
name.classList.remove("InvalidCharacterFlash");
error.classList.remove("error-message");
errorInfo.classList.remove("error-message");
name.style.backgroundColor = "";
error.style.backgroundColor = "";
error.innerHTML = "";
errorInfo.innerHTML = "";
}
I tried running a debugger in Vscode but it didn't seem to enter the portion of shouldValidate === true and seemed to be correctly keeping it false after entering the else if (name.tooShort).
The behavior I'm trying to get is for when I change the input from "a!" to "a" that it waits the 2.5 seconds and then displays the custom message for tooShort