dsol828 dsol828 - 1 month ago 12
Javascript Question

jQuery validation using values in array

I have a simple form and would like to add a custom jQuery validation rule. I would like the text field (bonuscode) to only have a handful of possible values. I assume I need an array of those values, but not knowing much javascript, I don't know where I'm going wrong here.

jQuery.validator.addMethod("equals", function(value, element, param) {
return this.optional(element) || value == param;
}, jQuery.format(""));

$(document).ready(function(){
$("#form").validate({
debug: false,
rules: {
bonuscode: {equals: ["code1", "code2"]}
},
messages: {
bonuscode: "That's not a Bonus Code!",
},
});
});

Answer

Having the bonus value in the javascript array is not a good solution. You can make the ajax request to the server and check the bonus value. Here is the sample code.

You can use the remote option in the validation plugin to check the bounus

$("#form").validate({
  debug: false,
  rules: {
    bonuscode: {
      required: true,
      remote: {
        url: "check-bonus.php",
        type: "post",
        data: {
          bonuscode: function() {
            return $("#bonuscode").val();
          }
        }
      }
    }
  }
});