1

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?

5
  • there is 'reValue', 'phoneValue' and 'phoneClass'... Commented May 16, 2012 at 20:11
  • 1
    You just need to massage your code a bit (sorry about that, couldn't resist!) Commented May 16, 2012 at 20:12
  • 4
    @DavidWolever How does that comment even suit in this case...? The OP has created a SSCE, and phrased a clear question. What else can he do before posting the question? Commented May 16, 2012 at 20:15
  • @bfavaretto :) stupid auto-correct ... Commented May 16, 2012 at 20:16
  • @RobW you are right. Radi, please forgive me for taking out my unrelated frustrations on StackOverflow. Commented May 18, 2012 at 4:54

2 Answers 2

2

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)) {
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help! I have been banging my head against the wall for the past 2-3 hours not knowing what is going on... Thanks a lot!
1

phoneValue.test(el.value) resolves to false. That is why the else if is not firing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.