添加自定义验证器到jquery验证插件不显示错误消息

时间:2017-10-21 22:50:52

标签: javascript jquery jquery-validate

我无法找到类似的解决方案来处理我所面临的问题。我正在使用jquery validate插件来验证表单。我添加了几个自定义验证器方法来验证下拉列表,另一个验证文本框。下拉验证工作正常,但文本框验证仅“部分”有效。我说'部分'因为实际的验证部分有效但是应该显示的错误信息不会显示。有问题的字段是id3文本字段,它与javascript相关联。

这是我的HTML:

<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">USA
      <br />
      <input class="form-check-input col-10" type="checkbox" name="uk" value="Y"> 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 :(问题自定义规则在CAPS中注释)

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;
 }

$("#id3").on("blur", function(){
  if(!checkName()){
  //display error: This Book name already exists!
 }
  else{
  //remove error message
 }
  console.log("The name entered is valid: " + checkName());
 });


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

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

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

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

  //2ND CUSTOM RULE - THIS RULE PARTIALLY WORKS, BUT ERROR DOES NOT DISPLAY
 $.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"
},

 //THE FIRST 2 STANDARD BUILT IN ERROR MESSAGES ARE DISPLAYED CORRECTLY,
 //BUT THE LAST CUSTOM ERROR MESSAGE - booknameExists - DOES NOT
'id3': {
  required: "Book name is required.",
  maxlength: "Book name cannot exceed 200 characters",
  booknameExists: "Book name already exists!"
}
}
});

css是小提琴,但为了完整起见,这里是:

 .hideDiv {
    display: none;
  }

.has-error {
   color: red;
 }

以下是小提琴的链接:https://jsfiddle.net/0puehapu/

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我终于搞清楚了。我的自定义验证器缺少一行代码。在错误修复之后,这就是我的自定义验证器现在的样子:

$.validator.addMethod("booknameExists", function(value){
   return checkName();
 }, "Book name must not pre-exist");

缺少的部分是:return checkName(); 没有为&gt; 10yrs搞乱w / validate插件,这是一个重新学习的过程,而且我不再是大学毕业了!感谢@Sparky的努力 - 将会赞同他的评论。

(PS:对于任何寻找完整代码的人来说,我在回复Sparky的帖子中发布的jsfiddle都有它 - 唯一的变化就是上面的代码片段)