0

Im trying to make some validation with javascript for a phone number field of a form.

I have taken some RegEx from another website and it almost works.

But the javascript does allow the form to submit if you place letters inbetween numbers like so "1234abc5678"

here is my validation code:

if (telephone==null || telephone=="")
  {
  alert("Telephone must be filled out");
  return false;
  }

var regexp = telephone.replace(/^[\s()+-]*([0-9][\s()+-]*){6,20}$/);
if (telephone.match(regexp))
  {
  alert("Telephone number is not valid");
  return false;
  }

Could someone help me with this code and tell me what is going wrong

After 1 more test I found that it allows letters within the numbers if I add a + at the beginning. I do need to allow the + at the start but obviously not the letters.

My required output would be for a phone number between 6 and 20 characters in length, which also allows a + at the start if one should be entered. any other characters should be invalid

4

5 回答 5

2

使用 JavaScript 验证电话号码

         var s ="123456";
        var filternumber = /^([0-9]+)$/;
        if((filternumber.test(s)==false)){
           alert ("not valid number");                
        }else {                               
          alert ("valid number");  
        }      
于 2013-06-19T10:53:54.100 回答
2

replace不做你认为它做的事。只需使用

var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;

你应该没事...

于 2013-06-19T10:42:19.377 回答
2

你为什么打电话String#replace?你只需要这样调用String#match(re)

var regex = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
if (telephone.match(regex))
  console.log("Telephone number is valid");
else
  console.log("Telephone number is not valid");

现场演示:http: //ideone.com/urCGLV

于 2013-06-19T10:46:07.710 回答
2
if (telephone==null || telephone=="") {
    alert("Telephone must be filled out");
    return false;
}

var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
if (! telephone.match(regexp)) {
    alert("Telephone number is not valid");
    return false;
}
于 2013-06-19T10:56:14.420 回答
0

你需要测试

var regexp = telephone.replace(/^+?\d{6,20}$/);
if (!regexp.test(telephone))   {
    alert("Telephone number is not valid");
    return false;
}
于 2013-06-19T10:42:46.613 回答