jQuery 验证:比较两个字段

jQuery Validate: compare two fields

我想检查在一个字段中输入的值是否小于在其他字段中输入的值。

Html:

<form id="bid_form_id">
    <input type="text" name="bid_price" id="bid_price_id" value="">
    <input type="text" name="bid_auto_decrement" id="bid_auto_decrement_id" value="">
</form>

jQuery:

<script>

    jQuery(document).ready(function ($) {

        $.validator.addMethod('le', function (value, element, param) {
            return this.optional(element) || value <= $(param).val();
        }, 'Invalid value');


        $('#bid_form_id').validate({
            errorElement: "small",
            rules: {
                bid_price:
                        {
                            required: true,
                            number: true

                        },
                bid_auto_decrement:
                        {
                            required: true,
                            number: true,
                            le: '#bid_price_id'
                        }
            },
            messages: {
                bid_auto_derement: {le: 'Must be less than bid price.'}
            }

        });
    });


</script>

'bid_auto_decrement' 值应小于 'bid_price' 值。 该脚本首次运行。如果我在第二个字段中输入较大的值,它会显示 'invalid value' 但之后如果我输入正确的值,它仍然会显示错误。

您可以使用:

$(function() {
    //Catch the forms submit event.
    $("FORM#bid_form_id").on("change", function(evt) {
        //Setup variables
        var valid = false;
        var max = $("#bid_price_id", this);
        var cur = $("#bid_auto_decrement_id", this);

        //Is the bid valid?
        valid = (parseInt(max.val()) > 0 && parseInt(max.val()) > parseInt(cur.val()) ? true : false);

        //If the bid is not valid...
        if ( !valid ) {
            //Stop the form from submitting
            evt.preventDefault();
            //Provide an error message (sorry for te use of alert!)
            alert("Oops!\n\nPlease make sure your bid is smaller than the previous.");
            //Focus on our textbox
            $("#bid_auto_decrement_id").focus();
        }

        //If the form is valid, it will submit as normal.
    });
});

虽然我很欣赏这没有使用您的 jQuery 验证器,但它展示了比较两个可预测值的基本原理。

希望对您有所帮助。我没有运行这个代码。

The script works for the first time. If I enter larger value in 2nd field, it shows 'invalid value' but after that if I enter correct values, it still shows error.

这是因为您的自定义规则是在 bid_auto_decrement 上声明的,这意味着您的自定义规则仅由 bid_auto_decrement 字段上的事件触发。

由于您想在 bid_price 的值更改时重新触发 bid_auto_decrement 字段的验证,因此您需要一个事件处理程序以编程方式触发 [=12] 的验证=] 字段.

$('[name="bid_price"]').on('change blur keyup', function() {
    $('[name="bid_auto_decrement"]').valid(); // <- trigger a validation test
});

工作演示:http://jsfiddle.net/o7vgejsk/

注意:您还在 messages 对象中将字段名称拼错为 bid_auto_derement,因此您的自定义消息被忽略了。

在对这些字段的值进行评估或进行任何数学运算时,您还需要使用 parseInt(),否则,它们将被视为字符串。

$.validator.addMethod('le', function (value, element, param) {
    return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, 'Invalid value');

这是添加自定义 JQuery 验证的示例代码。

这将验证最大输入并且最大输入将始终大于最小输入。

  <form id="menuItemTagsDetailsForm">

<div class="col-xs-12" id="item_tag_content_panel">
  <div class="form-group col-md-4">
    <label class="control-label" for="minimum_selection_for_bash_dish">* Minimum Selections</label>
            <input type="number" class="form-control valid" id="minimum_selection_for_bash_dish" name="minimum_selection_for_bash_dish" required="" data-rule-required="true" aria-required="true" aria-invalid="false">
    <label id="minimum_selection_for_bash_dish-error" class="error" for="minimum_selection_for_bash_dish" style="display: none;"></label>
  </div>
  <div class="form-group col-md-4">
    <label class="control-label" for="max_selection_for_bash_dish">* Maximum Selections</label>
            <input type="number" class="form-control error" id="max_selection_for_bash_dish" name="max_selection_for_bash_dish" required="" data-rule-required="true" aria-required="true" aria-invalid="true">
    <label id="minimum_selection_for_bash_dish-error" class="error" for="minimum_selection_for_bash_dish" style="display: none;"></label>
  </div>

  <div class="form-group col-md-4">
    <div class="form-group text-right">
        <button class="btn btn-success btn-sm" type="submit" name="saveTagsSubmit" value="saveTagsSubmit"><i class="glyphicon glyphicon-save"></i><span class="hidden-xs">&nbsp;Save</span></button>
    </div>
  </div>

</div>

</form>

将自定义规则添加到您现有的验证库

$.validator.addMethod('greaterThan', function (value, element, param) {
return this.optional(element) || parseInt(value) >= parseInt($(param).val());
}, 'Invalid value');
$("#menuItemTagsDetailsForm").validate({

     rules: {
       minimum_selection_for_bash_dish: {
           required: true,
           number: true

       },
       max_selection_for_bash_dish: {
           required: true,
           number: true,
           greaterThan: '#minimum_selection_for_bash_dish'
       }
   },
   messages: {
       max_selection_for_bash_dish: {
           greaterThan: 'Maximum selections is always geater then or equal to minimum selections.'
       }
   }
});