I am trying to create a form with some basic client side validation. In the form i have 3 input fields for, username, email and password. Initially they have a common class that is input. Also i attached a sibling paragraph element to these input elements, these paragraph element contains some input specification that has to be displayed to user if user enters something invalid.
In CSS i have basically created two classes, valid and invalid, valid just turns the border of input elements to green, and invalid turns border to red and sets the paragraph element opacity to 1 from 0(initial style).
In script file to check validity of user's input i have three boolean variables, isUserNameValid, isEmailValid, isPasswordValid, all these three are initially set to false.
Now i am adding these CSS classes during runtime as user inputs. Adding classes (valid and invalid) is working fine for first input element that is username input element, but as soon as i go to next input element that is email and type a single letter, script is adding class valid to email input element instead of invalid, even though isEmailValid is false.
I tried my best to figure out why it's adding class valid even though i am explicitly saying if the isEmailValid is equals to false add a class of invalid and remove class valid, instead it's doing the opposite.
I have attached the fiddle link, also i am not very much experienced in JavaScript, so, explanation in simple English is appreciated.
if(username.length > 5) {
isUserNameValid = true
}
if(email.length > 10) {
isEmailValid = true
}
if(password.length > 10) {
isPasswordValid = true
}
if(isUserNameValid === true && isEmailValid === true && isPasswordValid === true) {
loginButton.disabled = false
loginButton.style.cursor = 'pointer'
} else {
console.log('username',username, isUserNameValid)
console.log('email',email, isEmailValid)
console.log('password',password, isPasswordValid)
loginButton.disabled = true
loginButton.style.cursor = 'default'
if(isUserNameValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isEmailValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isPasswordValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isUserNameValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isEmailValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isPasswordValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
}
FIDDLE LINK: https://jsfiddle.net/weg9jy0c/5/