Steve Joiner
Steve Joiner

Reputation: 503

JQuery Validate select element not including default value

I am trying to validate a Select element as follows:

<select name="block_name" id="block-name">
 <option value="">Select Block</option>
 <option value="blockA">Block A</option>
 <option value="blockB">Block B</option>
</select>

which normally wouldn't be a problem if the rule was as Follows:

rules: {
 block_name: {
   required: true
 }
}

As I would just add class="required" to the select element. But I am using a function in the rule as follows:

rules: {
 block_name  {
  required: function(element) {
   return $("#blocks").val() >= 2;
        }
    }
}

which uses the following hidden field which has a data binding that determines the value:

<input type="hidden" name="blocks" id="blocks" value="<?php echo $row_rsCurrentUser['blocks']; ?>">

When using this function in the rule the class="required" does not work thus excepting the default option element <option value="">Select Block</option>

How can I get this to validate but not except the default option as a selection?

Thanks in advance

Upvotes: 1

Views: 1536

Answers (2)

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

You can add all kind of validation in your function:

$("#myform").validate({
  debug: true,
  rules: {
    block_name:  {
      depends: function(element) {
        var blocksIsValid = (Number($("#blocks").val()) >= 2);
        var block_nameIsValid = ($("#block_name").val() !== "");
        $('#output').text('#blocksIsValid:'+blocksIsValid+', #block_nameIsValid: '+block_nameIsValid);
        return blocksIsValid && block_nameIsValid;
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<form id="myform">
  <select name="block_name" id="block_name" required>
    <option value="">Select Block</option>
    <option value="blockA">Block A</option>
    <option value="blockB">Block B</option>
  </select>
  <input id="blocks" name="blocks" value=""/>
  <input type="submit" value="Validate"/>
  <p id="output"></p>
</form>

If you are not familiar with JS conditions, here are a few tips:

With || (same as OR) at least one of the conditions must be true;

With && (same as AND) all conditions must be true.

With ! (same as NOT) your condition will be flipped (true becomes false, false becomes true).

Read more https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals

Upvotes: 0

Barmar
Barmar

Reputation: 781974

I think you can define a new class rule, rather than using the built-in class="required".

$.validator.addClassRules("required_block2", {
    required: function(element) {
        return $("#blocks").val() >= 2;
    }
});

Then use class="required_block2" on these elements.

Upvotes: 1

Related Questions