I have a custom jQuery validate rule called fiftyCents() where there are two rules:
- if the item is free, one can “buy” it for $0.00 or they can pay greater than $0.50.
- if the item is NOT free, then they must pay at least the cost specified (stored in a hidden
cachedValueinput field).
So those are my two validation error messages. The problem I’m having in adding these to fiftyCents() is that I can only figure out how to evaluate it as true/false and if false, display a single message, e.g., "Amount must be $0.00 OR greater than $0.50.".
The solution to the JSfiddle (code below too) appears to be to make a message object that could be part of the fiftyCents() function. However, I don’t know how to return that along with evaluating true/false. Thoughts?
JS:
$('button').click(function(){
$('form').validate().form();
});
$.validator.addMethod("fiftyCents", function(value) {
var cachedValue=$('.purchaseModalAmtPaidCached').val();
var value = $('.purchaseModalAmtPaid').val();
var message="Amount must be $0.00 OR greater than $0.50.";
if(cachedValue>0) message='Amount must be at least'+cachedValue+'.';
return cachedValue<=value && (value==0 || (0.51<=value && value<=10000));
}, message);
$.validator.classRuleSettings.purchaseModalAmtPaid = { fiftyCents: true };
HTML:
<form>
<input class="purchaseModalPassword required" minlength="8" type="password"name="password" value="dddddddv" title="Please enter a valid password" />
<input type="text" title="Amount must be $0.00 OR greater than $0.50"
class="required purchaseModalAmtPaid" name="amt_paid" value="" />
<input type="hidden" class='purchaseModalAmtPaidCached required' name="AmtPaidCached" value="0.00" />
<button type='button'>Buy</button>
</form>
Ok I answered my own question. What I ended up doing is splitting up the two rules into their own custom methods. I used an
if/elsebefore either custom method is invoked to determine which of the two should be followed.Here’s the JSFiddle and code below:
JS:
});
HTML:
Note: A key to the HTML cooperating with jQuery validate is that if you give your inputs a
title=''attribute then that title will always be used, thus overriding the message in your custom rule. This is relevant in my case b/c there were two custom rules/messages and I’m not able to determine in advance of the HTML being rendered which one the user would see.