javascript - jquery 验证插件如果选中复选框则文本区域不能为空

标签 javascript jquery jquery-validate

我搜索了SO,有一个类似的问题,但那是用asp,但我的代码是纯jquery,而不是asp。

我的用例如下:

我有一个 html5 表单,带有各种 html 字段。我使用 jQuery 3.2.1 和 jquery 验证插件来验证字段。我能够验证所有文本输入、下拉菜单,但遇到依赖于复选框的文本区域问题。如果用户在文本区域(称为“描述”)中输入文本(至少 5 个字符),但没有选中 2 个复选框之一(ID 为“usa”),我需要显示错误消息。反之亦然 - 即,如果用户选中两个复选框之一(ID 为“usa”),但未在文本区域中输入任何文本(称为“描述”)(至少 5 个字符),则还需要显示错误消息。

 <form class="form-horizontal" name="paymentInformation"      id="paymentInformation" action="verifyOrder.cfm" method="post" role="form">
   <div class="form-group">
     <fieldset class="col-sm-12">

  <!-- Row 1 -->
  <div class="row">
    <div class="col-sm-6">
      <label for="booktype" class="col-6 col-form-label">
        Book Type *
      </label>
      <select class="custom-select col-4" id="booktype" name="booktype">
        <option selected value="">Select book type</option>
        <option value="val1">E-BOOK</option>
      </select>
    </div>

    <div class="col-sm-6">
      <label for="id2" class="col-6 col-form-label">
        Number
      </label>
      <input type="form-control" placeholder="Number" type="text" id="id2" name="id2" class="col-10">
    </div>

  </div>
  <!-- /Row 1 -->
  <!-- Row 2 -->
  <div class="row">
    <div class="col-sm-6">
      <label for="firstname" class="col-6 col-form-label">
        First Name *
      </label>
      <input type="form-control" type="text" id="firstname" name="firstname" class="col-12" placeholder="Name">
    </div>
    <div class="col-sm-6">
      <label for="id2" class="col-6 col-form-label">
        Book Name
      </label>
      <input type="form-control" placeholder="Book Name" type="text" id="id3" name="id3" class="col-10">
    </div>
  </div>
  <!-- /Row 2 -->
  <div class="row">
    <div class="col-sm-6">
      <label for="lastname" class="col-6 col-form-label">
        Last Name *
      </label>
      <input type="form-control" type="text" id="lastname" name="lastname" class="col-12" placeholder="Name">
    </div>
  </div>
  <!-- /Row 2 -->
  <label for="description" class="col-10 col-form-label">
    Country description
  </label>
  <textarea id="description" name="description" rows="4" class="form-control txtarea-rounded"></textarea>
  <div class="form-check">
    <label class="col-sm-6">Countries: </label>
    <br />
    <label class="form-check-label col-10">
      <input class="form-check-input col-10" type="checkbox" name="usa" value="Y" id="usa">USA
      <br />
      <input class="form-check-input col-10" type="checkbox" name="uk" value="Y" id="uk"> UK
    </label>
  </div>

</fieldset>
   </div>
   <div class="hideDiv">
     <input type="submit" name=btnSubmit value="PROCEED TO THE NEXT STEP &#xf054;" class="blueButton">
   </div>
 </form>

以下是我的 JavaScript:

  var authorlist = [{"AUTHOR":"DONNA       EDWARDS","COUNTRY":"USA","REGION":"MIDWEST"},{"AUTHOR":"EMERALD JONES","COUNTRY":"UK","REGION":"EU"},      {"AUTHOR":"SHAKESPEARE","COUNTRY":"UK","REGION":"EU"}];
  function checkName(){
    var nameIsValid = true;
    var nametocheck = $("#id3").val();
    $.each(authorlist, function(index, val){
//console.log(val.AUTHOR);
      if(val.AUTHOR.toUpperCase() == nametocheck.toUpperCase()){
    //console.log(val.AUTHOR);
    nameIsValid = false;
  return false;
}
    });
    return nameIsValid;
    }

  function checkForm() {
var formIsValid = checkName() && $("#paymentInformation").valid();
    if (formIsValid) {
$(".hideDiv").show();
    } else {
$(".hideDiv").hide();
    }
  }

  $("#booktype").on("change", function() {
    checkForm();
  });

  $("#paymentInformation").on("keyup", function() {
    checkForm();
  });

  // add the rule here
  $.validator.addMethod("valueNotEquals", function(value, element, arg) {
    return arg !== value;
  }, "Value must not equal arg.");

  //add 2nd rule here
  $.validator.addMethod("booknameExists", function(value,element,arg){

  }, "Book name must not pre-exist");

  $.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",
    highlight: function(element) {
      $(element).parent().removeClass('has-success').addClass('has-error');
    },
    unhighlight: function(element) {
      $(element).parent().removeClass('has-error').addClass('has-success');
    },
    errorPlacement: function(error, element) {
      if (element.parent('.input-group').length || element.prop('type') ===       'checkbox' || element.prop('type') === 'radio') {
  error.insertAfter(element.parent());
      } else {
  error.insertAfter(element);
      }
    }
  });

  $("#paymentInformation").validate({
    rules: {
      'booktype': {
        valueNotEquals: ""
      },
      'firstname': {
        required: true,
        maxlength: 200
      },
      'lastname': {
        required: true,
        maxlength: 200
      },
      'id3': {
        required: true,
        maxlength: 100,
  booknameExists: false

      }
    },
    messages: {
'booktype': {
  valueNotEquals: "Select a book type.",
},
'firstname': {
  required: "Enter your First Name.",
  maxlength: "Your First Name cannot exceed 200 characters"
},
'lastname': {
  required: "Enter your Last Name.",
  maxlength: "Your Last Name cannot exceed 200 characters"
},
'id3': {
  required: "Book name is required.",
  maxlength: "Book name cannot exceed 200 characters",
  booknameExists: "Book name already exists!"
}
   }
  });

这是整个事情的要点:https://jsfiddle.net/damon_matt/fsLza6m0/21/

最佳答案

来自官网:https://jqueryvalidation.org/validate/

示例:根据需要指定联系人元素和电子邮件地址,后者取决于选中通过电子邮件联系的复选框。

$("#myform").validate({
  rules: {
    contact: {
      required: true,
      email: {
        depends: function(element) {
          return $("#contactform_email").is(":checked");
        }
      }
    }
  }
});

所以在你的情况下是这样的:

rules: {
      'booktype': {
        valueNotEquals: ""
      },
      'firstname': {
        required: true,
        maxlength: 200
      },
      'lastname': {
        required: true,
        maxlength: 200
      },
      'id3': {
        required: true,
        maxlength: 100,
        booknameExists: false

      },
      'description': {
        required: {
            depends: function(element) {
              return $("#usa").is(":checked");
            }
        }
    },

关于javascript - jquery 验证插件如果选中复选框则文本区域不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184047/

相关文章:

javascript - 如何在网页上全屏显示幻灯片?

javascript - JQuery Validation - 限制多个文件上传数量的方法

jquery - 问题 - 在 jQuery 验证插件中输入有效数据和错误数据时,成功类不会消失

javascript - 创建一个新数组并在一行中将其插入其中 - Javascript OOP

javascript - 如何使用 mvvm 在日历中设置多个日期?

javascript - HTML5 地理定位、JavaScript 和数据库存储

javascript - 在 JavaScript 中检索 Controller 值

jquery - 如何通过jquery按Tab键迭代菜单的每个子菜单项?

php - 选中所有复选框并更改所有 Jquery 的颜色

javascript - jQuery 验证插件仅验证特定的表单字段