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.

1
  • Try alerting document.forms[0].elements[1] itself to see if the value is what you expect. Commented May 2, 2013 at 14:08

3 Answers 3

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?

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

1 Comment

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...
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;  
        }  
}

Comments

0

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

A comprehensive regex for phone number validation

Validate phone number with JavaScript

Comments

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.