AJJ
AJJ

Reputation: 897

Javascript validation issue?

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?

Upvotes: 0

Views: 66

Answers (2)

Ed_
Ed_

Reputation: 19098

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.

Upvotes: 4

adaniluk
adaniluk

Reputation: 431

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

Upvotes: 0

Related Questions