javascript 如何在 jquery 中验证整数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24981861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:41:18  来源:igfitidea点击:

How to validate Integer value in jquery

javascriptjqueryjquery-validate

提问by user3419304

I need to validate input field, it should be integer(0-100), if max_seat = 5 then min_seat should be less than or equal to max_seats.

我需要验证输入字段,它应该是整数(0-100),如果 max_seat = 5 那么 min_seat 应该小于或等于 max_seats。

<form class="cmxform form-horizontal" id="table_info" name="table_info"  method="post" action="">                                                       
<input class="span6 " id="max_seat"  name="default_seats" type="text" />
<input class="span6 " id="min_seats"  name="default_seats" type="text" />
</form>

and the jquery is looking like this, how to create rules in this type validation, thank you

和jquery看起来像这样,如何在这种类型验证中创建规则,谢谢

    $("#table_info").validate(
    {
        rules: {
            min_range :"required integer",
            max_seats:"required integer"
        },
        messages: {
            max_seats: "* Required",
            min_range: "* Required",
        }
    });

回答by Sparky

This is not how you declare multiple rules. (This shorthand style can only be used with onerule.)

这不是您声明多个规则的方式。(这种速记样式只能与一条规则一起使用。)

rules: {
    min_range :"required integer",
    max_seats:"required integer"
}

You must declare each rule separately. And for an integer, you can use the digitsmethod.

您必须分别声明每个规则。而对于一个整数,则可以使用digits方法

Your HTML is also not valid for this plugin...

您的 HTML 也不适用于此插件...

<input class="span6 " id="max_seat"  name="default_seats" type="text" />
<input class="span6 " id="min_seats"  name="default_seats" type="text" />

Each field must contain a uniquenameattribute and you would declare your rules based on that name. (Declare the messagesoption similarly)

每个字段都必须包含一个唯一的name属性,您将基于该属性声明您的规则name。(messages同样声明选项)

rules: {
    min_seats: { // <- this is the NAME attribute of the field, not ID
        required: true,
        digit: true
    },
    max_seats: { // <- this is the NAME attribute of the field, not ID
        required: true,
        digit: true
    }
}

To compare the two fields, you must use the .addMethod()methodand declare your new custom rule the same as above.

要比较这两个字段,您必须使用.addMethod()方法并声明与上述相同的新自定义规则。