Reputation: 25
I am trying to nest another if statement inside the following if statement for form validation. Basically I want the if statement to apply to all the fields (as it currently does) but then provide extra requirements for certain fields. the nested if statement is doing nothing right now. Ideally I would like to be able to have an extra parameter for the inputValidation function calls which I could set to true if I require that the field only accept non-numbers. But a nested if statement as I have written below which works would serve just as well!
const firstName = document.getElementById('fname');
const lastName = document.getElementById('lname');
const email = document.getElementById('email');
const fAddress = document.getElementById('first-line-address');
const city = document.getElementById('city');
const country = document.getElementById('country');
const postcode = document.getElementById('postcode');
const submitButton = document.getElementById('submit');
function inputValidation(element, greaterThan, lessThan) {
element.addEventListener('input', function(element) {
if (element.target.value.length >= greaterThan && element.target.value.length <= lessThan) {
submitButton.removeAttribute('disabled');
// nested if statements isNaN
if (element === 'firstName' || element === 'lastName' && isNaN(element.target.value)) {
submitButton.setAttribute('disabled', 'true');
}
} else {
submitButton.setAttribute('disabled', 'true');
}
})
}
inputValidation(firstName, 2, 15);
inputValidation(lastName, 4, 20);
inputValidation(email, 7, 40);
inputValidation(fAddress, 10, 40);
inputValidation(city, 3, 40);
inputValidation(postcode, 8, 8);
Upvotes: 0
Views: 345
Reputation: 2010
Your element
argument is HTMLElement, not a string.
Condition element === 'firstName'
will never be true, beacuse you are comparing two different types: HTMLElement to string.
Try
if (element === firstName || element === lastName && isNaN(element.target.value)) {
submitButton.setAttribute('disabled', 'true');
}
Upvotes: 1