如何缩短重复验证代码

时间:2019-08-11 16:22:09

标签: javascript jquery

$('#add_product_form').on('submit',function(){
    if ($('#product_date').val() == '') {
        $('#product_date').addClass('border-danger');
    }else{
        $('#product_date').removeClass('border-danger');
    }
    if ($('#product_name').val() == '') {
        $('#product_name').addClass('border-danger');
    }else{
        $('#product_name').removeClass('border-danger');
    }
    if ($('#select_category').val() == '') {
        $('#select_category').addClass('border-danger');
    }else{
        $('#select_category').removeClass('border-danger');
    }
    if ($('#select_brand').val() == '') {
        $('#select_brand').addClass('border-danger');
    }else{
        $('#select_brand').removeClass('border-danger');
    }
    if ($('#product_price').val() == '') {
        $('#product_price').addClass('border-danger');
    }else{
        $('#product_price').removeClass('border-danger');
    }
    if ($('#product_quantity').val() == '') {
        $('#product_quantity').addClass('border-danger');
    }else{
        $('#product_quantity').removeClass('border-danger');
    }
 })

这是具有许多字段的一种形式。我们如何缩短这段代码?我在香草Javascript中尝试了相同的代码,显然它包含更多的代码行。有没有更好的方法来编写这种类型的代码?

3 个答案:

答案 0 :(得分:2)

最好为重复的事情创建一个函数,例如:

function validate($selector) {
    $selector.toggleClass('border-danger', $selector.val() == '')
}

$('#add_product_form').on('submit',function(){
    validate($('#product_date'));
    validate($('#product_name'));
    validate($('#select_category'));
    validate($('#select_brand'));
    validate($('#product_price'));
    validate($('#product_quantity'));
});

答案 1 :(得分:1)

您可以使用each循环。

在元素中添加通用类将简化初始选择器或使用类似$(this).find(':input[required]').each...

$('#add_product_form').on('submit', function() {
  $('#product_date,#product_name,#select_category,#select_brand,#product_price,#product_quantity').each(function() {
      $(this).toggleClass('border-danger', !this.value);
  });
});

答案 2 :(得分:0)

不必在JavaScript中维护字段列表,而使用required attribute并在脚本中利用它。这也将利用浏览器的内置验证。如果您不想使用内置验证,则可以使用其他属性,如下所示。如果您想使用普通的required属性,只需使用它代替data-custRequired

$("#form").submit(function() {
  var valid = true;
  $(this).find("[data-custRequired]").each(function() {
    var itemValid = true;
    if (this.tagName === "FIELDSET") {
      itemValid = $(this).find(":checked").length > 0;           
    }
    //Otherwise validate normally
    else {
      itemValid = $(this).val() !== ""      
    }
    
    $(this).toggleClass("danger-border", !itemValid );
    if(!itemValid) 
    {
      valid = false;
    }
  });
  console.log("Form Valid = " + valid);
  
  return false;
})
label {
  display: block;
}

.danger-border {
  border: red 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
  <label>First Name <input type="input" name="firstName" data-custRequired /></label>
  <label>Last Name <input type="input" name="lastName" data-custRequired /></label>
  <label>Comment <input type="input" name="comment"></label>
  <fieldset data-custRequired>
    <legend>Can we contact you - required</legend>
    <label><input type="radio" name="contact"> Yes </label>
    <label><input type="radio" name="contact">No </label>
    <label><input type="radio" name="contact">Maybe </label>
  </fieldset>
  <input type="submit">
</form>

香草Javascript

不需要很多

document.getElementById("form").addEventListener("submit", function(event) {
  var requiredElements = this.querySelectorAll("[data-custRequired]");
  var valid = true;
  for (var i = 0; i < requiredElements.length; i++) {
    var itemValid = true;
    var el = requiredElements[i];
    if (el.tagName === "FIELDSET") {
      itemValid = el.querySelectorAll(":checked").length > 0;
    } else {
      itemValid = el.value !== "";
    }

    //To support IE 10 we don't use the inbuilt toggle
    if (itemValid) {
      el.classList.remove("danger-border");
    } else {
      el.classList.add("danger-border");
      valid = false;
    }
  }

  console.log("Form Valid = " + valid);
  event.preventDefault();
  return false;
})
label {
  display: block;
}

.danger-border {
  border: red 1px solid;
}
<form id="form">
  <label>First Name <input type="input" name="firstName" data-custRequired /></label>
  <label>Last Name <input type="input" name="lastName" data-custRequired /></label>
  <label>Comment <input type="input" name="comment"></label>
  <fieldset data-custRequired>
    <legend>Can we contact you - required</legend>
    <label><input type="radio" name="contact"> Yes </label>
    <label><input type="radio" name="contact">No </label>
    <label><input type="radio" name="contact">Maybe </label>
  </fieldset>
  <input type="submit">
</form>