I’m trying to create a custom validation method in JQuery and I can’t manage to make it work properly.
Here is what I want to do :
<div class="row">
<label for="fld-stories">Stories</label>
<select id="fld-stories" class="valid" name="stories" title="">
<option value="">--</option>
<option value="1" label="1">1</option>
<option value="2" label="2">2</option>
<option value="3" label="3">3</option>
<option value="4" label="4">4</option>
<option value="5" label="5">5</option>
</select>
</div>
<div id="row_master_bedroom_location" class="row">
<label for="fld-master_bedroom_location">Master Bedroom Location</label>
<select id="fld-master_bedroom_location" name="master_bedroom_location" title="">
<option value="up">Upstairs</option>
<option value="down">Downstairs</option>
</select>
</div>
If the user selects the master bedroom location to be upstairs (see second select), the number of stories for the house should be superior or equal to 2 (which is logical since the master bedroom can’t be upstairs if there is only one story).
To do so I try to add a custom method to my JQuery validator :
$.validator.addMethod('masterBedroomLocation', function(value, element, params) {
if (value == 'up' && $("#fld-stories").val() < 2){
return false;
}
}, 'You cannot select "Upstairs" for a one–story home');
I’m not sure how to get the value of another element in the form, I tried the JQuery old fashion way but it doesn’t seem to work.
For additional information, I add the custom method in a global javascript files, in a function that binds the JQuery validation to every forms that have a special class name.
I managed to make it work.
It looks like the Jquery selector
$(“#fld-stories”)
works properly.
For some reason I don’t know, the method works if I invert the way I do my check and return a true instead of a false.
Here is the new method :