0

I have this javascript function:

if (myform.telephone.value.length < 10){
jAlert ('Please enter at least 10 characters!',function(){$(myform.telephone).focus();});
return false;

If the user enters less than 10 characters, an alert is triggered. I need to modify the script so that the alert pops if the user enters less than 10 DIGITS (0,1,2,etc)..

How can i do this ?

0

2 Answers 2

2

Update: As the OP correctly pointed out, there was a bug in the previous method. I advise not to use isNan as it is broken. I've updated the answer, code below.

This can be easily done by mathcing the input against a regular expression and then checking if the resulting number has 10 or more digits. Like:

var validate = function(){
    var number = tryParseNumber(input.value);
    if(number.toString().length < 10){
        alert("Invalid input");
    } else {
        alert("Valid output: " + number);
    }
};

var tryParseNumber = function (value) {
  if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
    return Number(value);
  return false;
}    

See this Fiddle for a working example.

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

Comments

1

Try :

function phonenumber(inputtxt)  
{  
  var phoneno = /^\d{10}$/;  
  if((inputtxt.value.match(phoneno))  
        {  
      return true;  
        }  
      else  
        {  
        alert("message");  
        return false;  
        }  
}  

To valid a phone number like XXX-XXX-XXXX XXX.XXX.XXXX XXX XXX XXXX

function phonenumber(inputtxt)  
{  
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
  if((inputtxt.value.match(phoneno))  
        {  
      return true;  
        }  
      else  
        {  
        alert("message");  
        return false;  
        }  
}  

If you want to use a + sign before the number in the following way +XX-XXXX-XXXX +XX.XXXX.XXXX +XX XXXX XXXX use the following cod

function phonenumber(inputtxt)
{
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

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.