首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery验证:比较两个字段

jQuery验证:比较两个字段
EN

Stack Overflow用户
提问于 2015-09-15 21:18:44
回答 3查看 14.2K关注 0票数 2

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

Html:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
<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‘,但之后如果我输入正确的值,它仍然会显示错误。

EN

Stack Overflow用户

发布于 2015-09-15 21:47:05

您可以使用:

代码语言:javascript
复制
$(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验证器,但它展示了比较两个可预测值的基本原理。

我希望这能帮到你。我还没有运行过这段代码。

票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32587177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档