简体   繁体   English

jQuery仅验证十进制数

[英]jQuery Validate only decimal number

Does anyone know how I can validate a price format like the following 有人知道我如何验证以下价格格式

1.00 1200.00, but I also want to allow as 1 and 1200 1.00 1200.00,但我也想允许为1和1200

$.validator.addMethod('decimal', function(value, element) {
        return this.optional(element) || /^[0-9]+\.\d{1,3}$/.test(value);
    }, "Please enter a correct number, format 0.00");

jQuery.validator.setDefaults({
        debug: true,
        success: "valid"
    });

    $( "#myform" ).validate({
        rules: {
            field: {
                required: true,
                decimal: true
            }
        }
    });

^ I found this code, but it still allows commas. ^我找到了此代码,但仍允许使用逗号。 Basically I am looking for something like is numeric without the comma. 基本上,我正在寻找没有逗号的数字。

So basically only want to allow numbers and optional decimals. 因此,基本上只希望允许数字和可选的小数。

Any suggestion? 有什么建议吗?

Update: So the above works, but its forcing the requirement of decimal. 更新:所以上面的工作,但它强制十进制的要求。 How to make that optional so I can do 1200 or 1200.00? 如何使该可选,以便我可以执行1200或1200.00? Or maybe there is a way to just convert 1200 to 1200.00 ? 或者也许有一种方法可以将1200转换为1200.00?

My proposal to solve your problem is: 我为您解决问题的建议是:

 $.validator.addMethod('decimal', function(value, element) { return this.optional(element) || /^((\\d+(\\\\.\\d{0,2})?)|((\\d*(\\.\\d{1,2}))))$/.test(value); }, "Please enter a correct number, format 0.00"); $(function () { $("#frm").on('submit', function(e) { e.preventDefault(); $('#log').text('Form is valid? ' + $(this).valid().toString()); }); $("#frm").validate({ rules: { price: { required: true, decimal: true } } }); }); 
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script> <form id="frm"> Money: <input name="price" id="price" type="text"><br> <input id="submit" type="submit" value="Submit"> </form> <p id="log"></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM