javascript form not validating fields
Solution 1:
As Advait_Nair said, you need to remove all return false
in each conditions.
What I do in this case is setting a variable errors
(array) where I add every field with an error. This way I know if there was errors and what field got one.
This way you can do something like :
function checkInputs() {
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const subjectValue = subject.value.trim();
const msgValue = msg.value.trim();
var errors = []; // add errors array
if(usernameValue === '') {
setErrorForUser(username, 'Name cannot be blank');
errors.push('username');
}
else{
setSuccessForUser(username);
}
if(emailValue === '') {
setErrorForEmail(email, 'Email cannot be blank');
errors.push('email');
}
else if(!isEmail(emailValue)){
setErrorForEmail(email, 'Invalid email');
errors.push('email');
}
else {
setSuccessForEmail(email);
}
if(subjectValue === '') {
setErrorForSubject(subject, 'Subject cannot be blank');
errors.push('subject');
}
else{
setSuccessForSubject(subject);
}
if(msgValue === '') {
setErrorForMsg(msg, 'Message cannot be blank');
errors.push('message');
}
else{
setSuccessForMsg(msg);
}
if (errors.length > 0) {
// here you can display error message with fields list
return false;
}
return true;
}