检查长度,然后检查该值是否只是数字JavaScript

时间:2017-01-03 19:36:41

标签: javascript jquery validation

我正在尝试对3个文本框(电话号码)进行字段验证。理想情况下,我只想验证三个框中的任何一个包含值。否则,不应生成错误。此外,如果任何值放在文本框中,我想确保它们只是数字。

方案如下......

1.user在任何方框中都没有输入任何内容:没有任何反应 2.user将“12”输入方框#1,将“222”输入方框#2,将“4444”输入方框#3:这导致数字不完整。验证。
3.user输入有效长度的值。 EX:“11j”“222”“1222”:这不是有效值,因为它包含一个字母。验证

我当前的解决方案有点工作。除了它不允许用户将任何字段留空(方案1无效)。我该如何解决这个问题?

验证:

$("#editArea,#editPrefix,#editSuffix").blur(function () {
        var regex = /^[0-9]+$/;
        var phone = $("#editArea").val() + $("#editSuffix").val() + $("#editPrefix").val();
        var area=$("#editArea").val();
        var suffix=$("#editSuffix").val();
        var prefix=$("#editPrefix").val();
        if (phone.length > 0 && phone.length < 10||!regex.test(area)==true||!regex.test(suffix)==true||!regex.test(prefix)==true) {
            $("#editPhoneError").html('<font color="#cc0000">The number must be a numeric 10 digit value </font>');
            $("#editArea").addClass("validation");
            $("#editPrefix").addClass("validation");
            $("#editSuffix").addClass("validation");
        }
        else {
            $("#editPhoneError").html('<font color="#cc0000"></font>');
            $("#editArea").removeClass("validation");
            $("#editPrefix").removeClass("validation");
            $("#editSuffix").removeClass("validation");
        }
        $("#btnSave").prop("disabled", ($(":input.validation").length > 0));
    });   
}

标记:

 <div>
 <input id="editArea" maxlength="3" onkeyup="tabout(this,'editPrefix')" name="editArea" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Area" depends />
 </div>
 <div>
 <input id="editPrefix" maxlength="3" onkeyup="tabout(this,'editSuffix')" name="editPrefix" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Prefix" depends />
  </div>
  <div>
  <input id="editSuffix" maxlength="4" onkeyup="tabout(this,'editPrefix')" name="editSuffix" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Suffix" depends />
  </div>
  <span style="margin-left:-208px; margin-top:50px;" id="editPhoneError" value="0"></span>
  </div>

3 个答案:

答案 0 :(得分:2)

只需替换它:

if (phone.length > 0 && phone.length < 10||!regex.test(area)==true
       ||!regex.test(suffix)==true||!regex.test(prefix)==true) {

使用:

if (area.length > 0 && suffix.length > 0 && prefix.length > 0 &&
       (phone.length < 10 || !regex.test(phone)) {

请注意,||部分需要这些额外的括号,否则前面的&&运算符优先。

另外,请注意regex测试的简化,您可以将其应用于phone而不是单个部分。

其他改进意见

您实际上不必检查整个电话号码,只需检查当前输入值(针对maxlength属性),并保留validation类的存在其他输入字段未改变。另一方面,您应该在页面加载时验证所有三个字段,您可以使用trigger()进行验证。

最好尽可能避免使用HTML操作,在这方面,您可以在原始HTML中包含错误消息,然后隐藏/显示它。

对数字的相反测试更容易:/\D/测试是否存在任何非数字字符。

处理change事件而不是blur事件更为标准。

这是一个包含这些想法的片段:

$(function () {
  $('input.phone').change(function() {
    var v = $(this).val();
    // Only check current input:
    var err = v.length > 0 && (v.length < +$(this).attr('maxlength') || /\D/.test(v));
    // ...and only set the validation class on/off for current input
    $(this).toggleClass("validation", err);
    // Count if any has this class, so to show the message and disable the button
    err = $(".validation").length > 0;
    // Leave the message in place, just hide/show it
    $('#editPhoneError').toggleClass('show', err);
    $("#btnSave").prop("disabled", err);
  }).trigger('change'); // trigger at page load
});
.phone { width:70px; }
.error { color: #c00; visibility: hidden }
.validation { border: 3px solid #e00 }
.show { visibility: visible }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input maxlength="3" class="phone" name="editArea" type="text" value="" depends />
<input maxlength="3" class="phone" name="editPrefix" type="text" value="" depends />
<input maxlength="4" class="phone" name="editSuffix" type="text" value="" depends />
<div id="editPhoneError" class="error">The number must be a numeric 10 digit value</div>
<button id="btnSave">Save</button>

答案 1 :(得分:1)

你可以这样做:

JS

$(".phone-validation").blur(function () {
        var regex = /^[0-9]+$/;
        var phone = this.value;
        if (phone.length > 0 && phone.length < this.getAttribute("maxlength") && !regex.test(phone)) {
            $("#editPhoneError").html('<font color="#cc0000">The number must be a numeric 10 digit value </font>');
            $(this).addClass("validation");
        }
        else {
            $("#editPhoneError").html('<font color="#cc0000"></font>');
            $(this).removeClass("validation");
        }
        $("#btnSave").prop("disabled", ($(":input.validation").length > 0));
    });   
}

标记:

 <div>
 <input class="phone-validation" maxlength="3" onkeyup="tabout(this,'editPrefix')" name="editArea" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Area" depends />
 </div>
 <div>
 <input class="phone-validation" maxlength="3" onkeyup="tabout(this,'editSuffix')" name="editPrefix" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Prefix" depends />
  </div>
  <div>
  <input class="phone-validation" maxlength="4" onkeyup="tabout(this,'editPrefix')" name="editSuffix" style="float:left; width:70px;" type="text" value="@Model.Pharmacy.Suffix" depends />
  </div>
  <span style="margin-left:-208px; margin-top:50px;" id="editPhoneError" value="0"></span>
  </div>

答案 2 :(得分:0)

您应该考虑使用class代替id来使此表单更具可伸缩性。我已经简化了你的jQuery,这看起来效果很好:

https://jsfiddle.net/rh19hfyu/

<强> HTML

<div>
  <input class="phone" id="editArea" maxlength="3" onkeyup="tabout(this,'editPrefix')" name="editArea" type="text" />
</div>

<div>
 <input class="phone" id="editPrefix" maxlength="3" onkeyup="tabout(this,'editSuffix')" name="editPrefix" type="text" />
</div>

<div>
 <input class="phone" id="editSuffix" maxlength="4" onkeyup="tabout(this,'editPrefix')" name="editSuffix" type="text" />
</div>

 <span style="color:#cc0000; display:none;" id="editPhoneError" value="0">The number must be a numeric 10 digit value</span>

JS

  $(function() {

    $(".phone").on("blur", function () {
      var regex = /^[0-9]+$/,
          error = $("#editPhoneError"),
          phone = "";

      $(".phone").each(function() {
        phone = phone + $(this).val();
      });

      if (phone.length > 0) {
        //validate
        if(!regex.test(phone)) {
            error.show();
        }
        else {
            error.hide();
        }
      }
    });   

  });