代码之家  ›  专栏  ›  技术社区  ›  Glyn

HTML-jQuery blur(function()在条目上触发,然后循环

  •  0
  • Glyn  · 技术社区  · 6 年前

    我正在验证两个电话号码。第一个电话号码验证工作正常;但是,如果第一个电话号码无效,然后我转到第二个电话号码,则在我输入任何数据之前,会触发第二个电话号码验证,并循环“invalid phone number 1c”,直到我关闭选项卡。

    如果我输入一个无效的电话号码,然后转到第二个电话号码以外的另一个字段,我只会收到一条错误消息(例如,在第一个电话号码中输入“9999999”,然后单击另一个文本输入字段,例如State)。

    $("#telephone1").blur(function() {
      validatePhoneNumber($(this).val(), this.id);
    });
    
    $("#telephone2").blur(function() {
      validatePhoneNumber($(this).val(), this.id);
    });
    
    function validatePhoneNumber(phone_number, id) {
      var formatted = "";
      //remove all non-digits
      phone_number = phone_number.replace(/\D/g, '');
      //if number starts with 61, replace 61 with 0
      if (phone_number.match(/^61/)) {
        phone_number = "0" + phone_number.slice(2);
      }
    
      if (phone_number.match(/^04/)) {
        if (phone_number.length === 10) {
          var formatted = phone_number.replace(/(\d{4})(\d{3})(\d{3})/g, "$1 $2 $3");
        } else {
          alert('Invalid phone number 1a');
        }
      } else if (phone_number.match(/^02|03|07|08/)) {
        if (phone_number.length === 10) {
          var formatted = phone_number.replace(/(\d{2})(\d{4})(\d{4})/g, "($1) $2 $3");
        } else {
          alert('Invalid phone number 1b');
        }
      } else if (phone_number.length === 8) {
        alert('Please use Area Code for landline numbers');
      } else {
        alert('Invalid phone number 1c');
      }
      //update
      $('#' + id).val(formatted);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="form-group row">
      <label for="telephone1" class="text-right col-lg-2 col-md-2 col-sm-2 col-xs-2 col-form-label">Telephone:</label>
      <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
        <input type="text" id="telephone1" name="telephone1" placeholder="Telephone 1">
      </div>
    </div>
    
    <div class="form-group row">
      <label for="telephone2" class="text-right col-lg-2 col-md-2 col-sm-2 col-xs-2 col-form-label"></label>
      <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
        <input type="text" id="telephone2" name="telephone2" placeholder="Telephone 2">
      </div>
    </div>
    1 回复  |  直到 6 年前
        1
  •  2
  •   Mike Young    6 年前

    我认为这只是使用 alert 对于错误消息,使用 onblur onchange blur 事件可能会因为几个不同的原因被调用,正如他们在文档中提到的 change 当元素失去焦点时检查值的变化