Ikhlak S.
Ikhlak S.

Reputation: 9024

jquery validation plugin if statement

How would you go about validating a field if a dropdown equals to a certain value.

Example:

HTML

<form id="foo">
    <!-----Dropdown----->
    <select name="budget_type">
        <option value="fixed" <?php if($budget_type=="fixed" ){echo "selected";} ?> >Fixed</option>
        <option value="hourly" <?php if($budget_type=="hourly" ){echo "selected";} ?> >Hourly</option>
    </select>
    <!-----Field----->
    <input id="dollar" type="text" name="budget" style="text-indent:17px;" value="<?php echo $budget; ?>" />
</form>

jQuery:

$('#foo').validate({
    rules: {
        budget: {
            required: true,
            notEquals: "0",
            digits: true,
            min: 50,
        }
    },

    messages: {
        budget: {
            required: "Please enter a value",
            min: "Minimum $ {0}",
        }
    }
});

So, if budget_type is fixed then minimum budget is 50 but if budget_type is hourly then minimum budget is 10. I tried the if() function but don't really know how and where to put the code.

Upvotes: 0

Views: 84

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can change the min rule to pass the value dynamically

jQuery(function($) {
  $('#foo').validate({
    rules: {
      budget: {
        required: true,
        digits: true,
        min: function() {
          return $('select[name="budget_type"]').val() == 'fixed' ? 50 : 10
        },
      }
    },
    messages: {
      budget: {
        required: "Please enter a value",
        min: "Minimum $${0}",
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="foo">
  <select name="budget_type">
    <option value="fixed">Fixed</option>
    <option value="hourly">Hourly</option>
  </select>
  <input id="dollar" type="text" name="budget" style="text-indent:17px;" value="20" />
  <input type="submit" value="Save" />
</form>

Upvotes: 1

Related Questions