Reputation: 413
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!",
},
});
});
Upvotes: 3
Views: 4082
Reputation: 126042
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/
Upvotes: 1
Reputation: 128
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();
}
}
}
}
}
});
Upvotes: 1