John John - 1 month ago 6x
HTML Question

Applying validation on condition using jQuery Validate

Good morning guys, I wonder if you may help me on this issue: I'm applying a validation to a select element as required when another input value meets a condition. I'm using the validation jQuery plugin in order to do it. This is the pseudo-code:

if(textbox == "valueX"){mySelectEelement is required;}
(means that I must choose one value from the select element.). So for some reason the select element is not taking the validation I want to apply.

Please take a look on the full sample code I created for this purpose at Plunker:

<html lang="en">
<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>

$( function() {
//debug: true,
success: "valid"

$( "#myform" ).validate({
rules: {
borough: {
required: false

$('#state').on('change', function () {
if ($(this).val().toUpperCase() == "NY" || $(this).val().toUpperCase() == "NEW YORK") {
$('#borough').rules('add', {
required: true
} else{
} );

<form id="myform">
<p id="pid"></p>
<input id='text' type='text' value='other'/>
<input type="text" id="state" name="state" />

<select name="borough" id="borough">
<option value="" select="selected"></option>
<option value="Staten Island">Staten Island</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Queens">Queens</option>
<option value="NY">NY</option>
</form></body> </html>



No need for external handlers and functions. You would use the depends property under required within the rules object to contain your conditional logic...

    rules: {
        borough: {
            required: {
                depends: function(element) {
                    if ($('#state').val().toUpperCase() == "NY" || $('#state').val().toUpperCase() == "NEW YORK") {
                        return true;
                    } else {
                        return false;