3

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!",
        },
    });
});

2 Answers 2

1

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();
          }
        }
      }
    }
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Why is it bad practice to include the values in the javascript? Can you show me what check-bonus.php would have to look like? Thanks so much for your help!
Got it now. My final solution posted in the OP for other's reference. Thanks.
@dsol828: It's a bad practice because the user of your site could just "view source" and see the bonus codes.
@dsol828 Please don't edit the solution (which is right here) into your question. Answer your own question instead.
1

Assuming this is actually your use case, @jems is probably correct in saying you should check this kind of thing in server-side code. However, your custom rule is not far off:

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's not a Bonus Code!",
        },
    });
});

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

1 Comment

$.inArray(value, param) > 0 should be $.inArray(value, param) > -1 See api.jquery.com/jQuery.inArray

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.