So I am working on a pure Javascript validation and I have some questions about its performance of it. How it works, the function runs the validation function when a “blur” event happens, however, during debugging, I see that all 3 fields are being validated (or at least I think that is what happening) shown in the picture below:
So, now I am thinking, is there a way to adjust the code, so that when the “blur” event happens, only 1 field is being validated and invoked? Or am I misunderstanding the way it should work?
The validation code is here below:
const mailValidPattern = new RegExp(/^[w-]+@([w-]+.)+[w-]{2,4}$/);
const passValidPattern = new RegExp(/(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}/);
function isValidLength(minAllowedLength, maxAllowedLength, inputElement) {
return inputElement >= minAllowedLength && inputElement <= maxAllowedLength;
}
const formInputs = document.querySelectorAll(".form__input");
formInputs.forEach(inputElement => {
inputElement.addEventListener("blur", e => {
e.target.classList.remove("form__input--error")
e.target.parentElement.querySelector(".form__input-error-message").textContent = " ";
const targetId = e.target.id
const validationMap = {
signupEmail: () => {
const targetValue = e.target.value;
const isValidEmail = targetValue.match(mailValidPattern);
const emailValidationText = "Invalid email format!";
const validLength = !isValidLength(6, 50, e.target.value.length);
!isValidEmail && validLength && inputErrorToggle(inputElement, emailValidationText)
},
signupUsername: () => {
const validLength = isValidLength(8, 50, e.target.value.length);
const userNameValidationText = "Username must be at least 8 characters!"
!validLength && inputErrorToggle(e.target, userNameValidationText)
},
signupPassword: () => {
const targetValue = e.target.value;
const isValidPassword = !!targetValue.match(passValidPattern);
const passwordValidationText = "Password must be at least 8 characters, including 1 uppercase letter and a number!"
!isValidPassword && inputErrorToggle(inputElement, passwordValidationText)
}
}
validationMap[targetId]();
})
});
If needed, I will provide the whole code in a codepen