Reputation: 897
I have written some javascript to validate a phone number field if something is entered (it is an optional field) but it doesn't seem to be working, if i enter wrong values it still submits. Here is my code:
<script>
function validatePhone()
{
var num1 = document.getElementById('workno');
if (num1 !== null)
{
regex = /\(\d{2}\)\d{8}/;
}
if (!num1.match(regex))
{
alert('That is not a correct telephone number format');
return false;
}
}
</script>
<form name="eoiform" form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validatePhone();">
<input type="text" id="workno" name="workno">
<input type="submit" name="submit" id="submit" value="submit">
</form>
Can anyone spot my mistake?
Upvotes: 0
Views: 210
Reputation: 780714
In addition to the problems noted in the other answers, you should also anchor the regexp. Otherwise, it will allow extra characters outside the phone number.
function validatePhone()
{
var num1 = document.getElementById('workno').value;
if (num1 !== "" && !num1.match(/^\(\d{2}\)\d{8}$/))
{
alert('That is not a correct telephone number format');
return false;
}
}
Upvotes: 0
Reputation: 175748
Your num1
variable contains an element object, not its value so can't be tested with a regexp as it stands.
It will only ever by null if the element does not exist; it will be "" if its got no value.
function validatePhone()
{
var num1 = document.getElementById('workno').value;
if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/))
{
alert('That is not a correct telephone number format');
return false;
}
}
You also have the invalid form method="POST"
in your HTML.
Upvotes: 2
Reputation: 2189
Maybe you should select the value from the Input. Can you try
if (!num1.value.match(regex))
Upvotes: 0