-1

I have a function written to validate a form where a phone number must be entered. What i am trying to make it do is that if there is a number entered it makes sure that the number is in the correct format, meaning that the field is not mandatory. The problem i am having is that if the field is left empty (which is acceptable) it still alerts with the message "That is not correct telephone number format" when instead it should just not validate the field at all, if it is empty. Here is the code i am using:

function validateHome() {
    var num2 = document.getElementById('homeno').value;

    if (num2 !== "" && !num2.match(/\(\d{2}\)\d{8}/)) {
        alert('That is not correct telephone number format');
        return false;
    }
    return true;
}

Could anyone help me with pointing out my mistakes?

5
  • What is the value of num2 when it's alerting but shouldn't? Commented May 30, 2013 at 12:53
  • a fiddle with also the html would be helpful Commented May 30, 2013 at 12:54
  • @MattBall i just leave the field empty. I want it to only validate if the field has an entry, leaving the field empty is allowable in which case of course the function shouldn't validate it. Commented May 30, 2013 at 12:56
  • Yes, I understand that, but that does not answer my question. Try a console.log(num2) or use a breakpoint to see why the num2 !== "" check is true when you think it should be false. Commented May 30, 2013 at 12:58
  • @MattBall != would work here. !== is an explicit (exactly equal to) in type and value comparison. Which if the value is undefined would not be the case. Undefined would equate to a falsy value but is not exactly equal to an empty string. This is why if(num2) or if(num2 != "") should both work Commented May 30, 2013 at 13:21

2 Answers 2

4

The value of num2 may be undefined if it's empty.

A better approach is probably:

if (num2 && !num2.match(/\(\d{2}\)\d{8}/))

Which will check that num2 is actually defined and not blank.

Sign up to request clarification or add additional context in comments.

Comments

0

shouldn't it be if (num2 == "" || !num2.match(/\(\d{2}\)\d{8}/)) ?

2 Comments

No, it shouldn't. The alert should only happen if the field is non-empty and does not match the regex.
Just change to num2 != "" or as Ed has put num2 which just checks that num2 is truthy (Same thing)

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.