I have a select "ArrearsLHOLocation" that has an option "None Selected" with a value of -1 and all other selectable values are greater than 0.
Here is the rule defined in my javascript
$("#ArrearsLHOLocation").rules("add", {
min: {
depends: function (elem) {
return $("#rbArrearsLHO[value='True']").is(":checked") ? 0 : -1;
}
},
messages: {
min: "You have stated that the applicant/coapplicant have LHO arrears but you have not stated where!"
}
});
Here are the watches as observed in Chrome.
$("#rbArrearsLHO[value='True']").is(":checked") ? 0 : -1: 0
$("#rbArrearsLHO[value='True']").is(":checked"): true
$("#ArrearsLHOLocation").val(): "-1"
$("#ArrearsLHOLocation").val() >=($("#rbArrearsLHO[value='True']").is(":checked") ? 0 : -1): false
This page successfully submits, incorrectly. If I toggle the radio button and the watches appear like this:
$("#rbArrearsLHO[value='True']").is(":checked") ? 0 : -1: -1
$("#rbArrearsLHO[value='True']").is(":checked"): false
$("#ArrearsLHOLocation").val(): "-1"
$("#ArrearsLHOLocation").val() >=($("#rbArrearsLHO[value='True']").is(":checked") ? 0 : -1): true
This page is stopped from being submitted and my error message is displayed.
What am I doing wrong?
Steve
--Snippet of HTML as requested--
<td>Do they have arrears?</td><td>
Yes <input id="rbArrearsLHO" name="rbArrearsLHO" type="radio" value="True" />
No <input checked="checked" id="rbArrearsLHO" name="rbArrearsLHO" type="radio" value="False" />
</td>
</tr>
<tr>
<td colspan="2">
<blockquote>
If YES, Where?
<select data-val="true" data-val-number="The field ArrearsLHOLocation must be a number." id="ArrearsLHOLocation" name="ArrearsLHOLocation">
<option value="-1">None Selected</option>
<option value="4">Location 1</option>
<option value="6">Location 2</option>
<option value="5">Location 3</option>
<option value="7">Location 4</option>
</select>
</blockquote>
</td>
</tr>
A
select
can only berequired
or not. I've never seen themin
rule used on aselect
to force the user to choose an option.Your
"None Selected"
option should containvalue=""
and then when you declare therequired
rule on this, the user will be forced to select any option other than"None Selected"
.Then your depends parameter would simply need to return a boolean to state whether the user needs to select an option.
DEMO: http://jsfiddle.net/7k2zg7rv/
EDIT:
Since you want to keep your first
option
asvalue="-1"
, you'll need to create a custom rule/method using theaddMethod()
method that recognizes your firstoption
as invalid.Updated DEMO: http://jsfiddle.net/7k2zg7rv/2/
Looking at jquery.validate I found that depends should only ever evaluate to true/false. So modifying the min to have [param : 0] which would have been the min when I needed it. Then changing the depends to evaluate to true when the minimum should be in effect solved this issue.
DEMO: FIDDLE (forked from @Sparky's previous fiddle)