简体   繁体   中英

Adding custom validator to jquery validate plugin not displaying error message

I couldn't find a similar solution to the issue I'm facing on SO. I'm using jquery validate plugin to validate a form. I've added a couple of custom validator methods to validate a drop down and another for validating a text box. The drop down validation works fine, but the text box validation only 'partially' works. I say 'partial' because the actual validation part works but the error message that is supposed to be displayed, does not display. The field in question is the id3 text field, and it's associated javascript.

This is my 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>

Here is my javascript: (Problem custom rule is commented in 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!"
}
}
});

The css is in the fiddle but for the sake of completeness, here it is:


 .hideDiv {
    display: none;
  }

.has-error {
   color: red;
 }

Here is the link to the fiddle: https://jsfiddle.net/0puehapu/

Any help is appreciated!

I finally got this figured out. My custom validator was missing a single line of code. This is how my custom validator looks now, after the bug fix:

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

The missing piece was: return checkName(); Not having messed w/ validate plugin for >10yrs, it was a re-learning process, and I'm not a college grad anymore! Thx to @Sparky for his efforts - will be upvoting his comment.

(PS: for anyone looking for the complete code, the jsfiddle that I posted in my reply to Sparky has all of it - the only change is the above snippet)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM