【问题标题】:Problem with form validation (phone numbers)表单验证问题(电话号码)
【发布时间】:2010-03-07 01:43:35
【问题描述】:

好的,我有一个验证脚本,可以检查表单上的所有内容 - 但无论其中有什么,它都会将电话号码字段标记为错误。我已经尝试了几种不同的方法,但我无法弄清楚我做错了什么。

验证的脚本部分是...

    if (testPattern(phone1, /^\d{3}$/)== false) { // checking phone length
        valid = false;
    }
    if (testPattern(phone2, /^\d{3}$/)== false) {
        valid = false;
    }
    if (testPattern(phone3, /^\d{4}$/)== false) {
        valid = false;
    }

功能码是……

function testPattern(field, reg2) {
    var trueOrfalse = reg2.test(field)
    if (trueOrfalse == false) {
        field.style.backgroundColor="yellow";  // if false, change colors and return false
        field.style.color="red";
        return false;
    }
    else {
        field.style.backgroundColor="white"; // if true, change colors and return true
        field.style.color="black";
        return true;
    }
}

【问题讨论】:

    标签: javascript validation forms


    【解决方案1】:

    也许

    var trueOrfalse = reg2.test(field)
    

    应该是

    var trueOrfalse = reg2.test(field.value)
    

    添加:

    另外,请记住,在布尔上下文中进行评估时,您不必比较真假。 (使用值本身或否定)。最好按照变量的含义命名变量,而不是“真或假”这是我的重写:

    if (!testPattern(phone1, /^\d{3}$/)) { // checking phone length
        valid = false;
    }
    if (!testPattern(phone2, /^\d{3}$/)) {
        valid = false;
    }
    if (!testPattern(phone3, /^\d{4}$/)) {
        valid = false;
    }
    
    
    
    function testPattern(field, reg2) {
      var good = reg2.test(field.value);
      if (good) {
          field.style.backgroundColor="white"; // if good, change colors
          field.style.color="black";
      }
      else {
          field.style.backgroundColor="yellow";  // if bad, change colors
          field.style.color="red";
      }
      return(good);
    }
    

    【讨论】:

    • +1 用于指定您应该按照变量的含义命名变量。
    【解决方案2】:

    不是您问题的实际答案,因为您发布的 sn-ps 本质上没有任何问题,但这对于评论来说太大了。

    你的代码真的是多余的!

    您可以将整个第一部分表示为:

    valid = testPattern(phone1, /^\d{3}$/) &&
            testPattern(phone2, /^\d{3}$/) &&
            testPattern(phone3, /^\d{4}$/)
    

    功能代码为:

    function testPattern(field, reg2) {
        var test_result = reg2.test(field)
    
        if (test_result) {
            field.style.backgroundColor = "white";
            field.style.color = "black";
        } else {
            field.style.backgroundColor = "yellow";
            field.style.color = "red";
        }
    
        return test_result;
    }
    

    或者更简洁:

    function testPattern(field, reg2) {
        var test_result = reg2.test(field)
    
        field.style.backgroundColor = test_result ? "white" : "yellow";
        field.style.color = test_result ? "black" : "red";
    
        return test_result;
    }
    

    是不是更容易阅读?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2012-03-04
      • 2017-03-13
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多