0

I have a form with three elements. I want to validate the phone number when the user enters it. If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox.

I have written some code but am completely stumped. The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. My code looks like this:

<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
} 
</script>

<form>
  <strong>FULLNAME: </strong><input type="text" / id="name"><br />
  <strong>PHONE NR: </strong><input type="text" id="phone"  onblur="validateForm()" />
  <strong>NATIONALITY</strong><input type="text" id="nat" /><br />
  <input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>

Thank you in advance for all your answers and help.

halfer
  • 19,824
  • 17
  • 99
  • 186
Timothy Coetzee
  • 5,626
  • 9
  • 34
  • 97

3 Answers3

4

Change

document.forms[0].elements[1]

to

document.forms[0].elements[1].value

You were testing the element itself, not the element's value.

jsFiddle example

BTW, if someone enters a phone number with a dash or parenthesis (e.g. (555) 123-4567) what do you expect to happen?

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    Thank you for very much for you clear answer. It worked great. To be honest I have not thought about what would happen if someone puts in a dash. From reading some of the responses I can see that some patterns will need to be used. Unfortunately I dont understand the code... – Timothy Coetzee May 02 '13 at 14:25
1

Here you will find many exemple to achieve your goal :

for example if you can use only number :

function phonenumber(inputtxt)  
{  
  var phoneno = /^\d{10}$/;  
  if((inputtxt.value.match(phoneno))  
        {  
      return true;  
        }  
      else  
        {  
        alert("message");  
        return false;  
        }  
}
Francois Borgies
  • 2,378
  • 31
  • 38
0

You should do it with a regular expression. See here:

A comprehensive regex for phone number validation

Validate phone number with JavaScript

Community
  • 1
  • 1
Levi Kovacs
  • 1,159
  • 8
  • 14