JQuery validation using values ​​in an array

I have a simple form and would like to add a custom jQuery validation rule. I would like the textbox (bonus code) to have only a few possible values. I guess I want an array of these values, but not knowing a lot of javascript, I don't know where I went 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 not a Bonus Code!",
        },
    });
});

      

+3


source to share


2 answers


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

You can use remote parameter in validation plugin to check bounus



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

      

+1


source


Assuming this is actually your use case, @jems is probably correct in saying that you should test this in server-side code. However, your custom rule is just around the corner:

jQuery.validator.addMethod("equals", function(value, element, param) {
    return this.optional(element) || $.inArray(value, param) >= 0; // <-- Check if the value is in the array.
}, jQuery.format(""));

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

      



Example: http://jsfiddle.net/AApJx/

+1


source







All Articles