0

更新:

如果我输入 9 位数的电话号码并接受 10 位数的电话号码,下面的脚本将引发错误......但它也只会接受一个数字 - 我怎样才能阻止这种情况发生。

对于收集器字段,我需要它只接受 11 个数字。

我正在尝试修改我的验证码以验证电话号码,这似乎是一项很容易的任务,但我无法让它正常工作。

脚本应检查它是否为 9 位长、空格、破折号或没有空格都可以。如果没有输入电话,它应该给出所需的错误。例如,如果该字段仅输入 8 位数字,则应给出无效电话错误。

请参阅此 jsfiddle 的代码 - http://jsfiddle.net/5zFqS/7/

function validate_required(field,alerttxt) {
  with (field) {
    if (value==null||value=="") {
      alert(alerttxt);return false;
    } else {return true;}
  }
}

function validate_email(field,alerttxt) {
  with (field) {
    apos=value.indexOf("@");
    dotpos=value.lastIndexOf(".");
    if (apos<1||dotpos-apos<2)
      {alert(alerttxt);return false;}
    else {return true;}
  }
}

function validate_Phone(field,alerttxt) {
    var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
    if(field.value.match(phoneno))  {
      alert(alerttxt);return false;
    } else {return true;}
  }


function validate_collector(field,alerttxt) {
  var collect = /^\d{12}$/;  
    if(field.value.match(collect))  {
      alert(alerttxt);return false;
    } else {return true;}

}

function validate_form(thisform) {
  with (thisform) {
    if (validate_required(firstName,"Please enter your First Name")==false)
    {firstName.focus();return false;}

    if (validate_required(lastName,"Please enter your Last Name")==false)
    {lastName.focus();return false;}

    if (validate_required(email,"Please enter your Email Address")==false)
    {email.focus();return false;}

    if (validate_email(email,"Please enter a valid Email Address")==false)
      {email.focus();return false;}

    if (validate_required(phone,"Please enter your Phone")==false)
    {phone.focus();return false;}

    if (validate_Phone(phone,"Please enter a valid Phone Number")==false)
    {phone.focus();return false;}

    if (validate_required(province,"Please select your Province")==false)
    {province.focus();return false;}

    if (validate_required(collector,"Please enter Collector Number")==false)
    {collector.focus();return false;}

    if (validate_collector(collector,"Please enter a valid Collector Number")==false)
    {collector.focus();return false;}



    }
  }

我想我有一个语法错误,但我看不到它。

4

2 回答 2

4

You need to remove the semi-colon at the end of this line:

if (field.match(/^\d{9}/));

You said that spaces etc., should be okay. In which case, you'll need to remove (or ignore) them:

var reg = /\D/g;    // \D identifies non-digit characters, g means 'global'
var stripped = "888-777 66st".replace(reg,"");
// returns: 88877766

Also, use of with is not recommended

as it may be the source of confusing bugs and compatibility issues

MDN reference

于 2013-07-02T20:59:34.753 回答
0

代替

if (field.match(/^\d{9}/))

用这个

if (!field.match(/\d{9}/))
于 2013-07-02T21:07:02.713 回答