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?
num2when it's alerting but shouldn't?console.log(num2)or use a breakpoint to see why thenum2 !== ""check istruewhen you think it should befalse.!=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 whyif(num2)orif(num2 != "")should both work