Reputation: 271
I am doing a form validation and having troubles with my code:
var reValue = /^\s*$/;
var phoneClass = /(^|\s)phoneValidate(\s|$)/;
var phoneValue =
/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/;
for (var i=0; i < iLen; i++) {
el = allElements[i];
if(phoneClass.test(el.className) && reValue.test(el.value)){
// The field is empty.
aMessages += 'Please enter a phone number in: '+ el.name +'.\n';
}
else if (phoneClass.test(el.className) && phoneValue.test(el.value)) {
// The field is not a valid phone number
// Advise user to fix it
aMessages += 'Please enter a valid phone number in: '+ el.name +'.\n';
}
}
The first IF statement works and displays the massage if the field is empty, but the ELSE IF for some reason does not... What am I doing wrong?
Upvotes: 1
Views: 2656
Reputation: 707436
Based on looking at your regex, I think you need to invert the logic on the phoneValue
test. You want the else if
clause to execute when it does NOT match the phoneValue
regex like this:
else if (phoneClass.test(el.className) && !phoneValue.test(el.value)) {
Upvotes: 2
Reputation: 3300
phoneValue.test(el.value)
resolves to false
. That is why the else if
is not firing.
Upvotes: 1