jquery验证插件if语句

时间:2015-10-08 08:24:53

标签: javascript jquery validation

如果下拉列表等于某个值,您将如何验证字段。

示例:

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}",
        }
    }
});

因此,如果预算类型是固定的,那么最低预算是50,但如果budget_type是每小时,那么最低预算是10.我尝试了if()函数但不知道如何以及在何处放置代码。

1 个答案:

答案 0 :(得分:1)

您可以更改min规则以动态传递值

&#13;
&#13;
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}",
      }
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;