jQuery 验证十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10790261/
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-08-26 09:45:47  来源:igfitidea点击:

Validating Decimal Numbers

jqueryjquery-validate

提问by black_belt

I have a form and I am using jQuery validation plugin to validate it. Now I am trying to validate decimal number input.

我有一个表单,我正在使用 jQuery 验证插件来验证它。现在我正在尝试验证十进制数字输入。

I have tried the following code, but its not working. Is the problem with the regular expression or the way of writing the custom rule is wrong in my code?

我已经尝试了以下代码,但它不起作用。是正则表达式的问题还是我的代码中自定义规则的编写方式有问题?

 rules: {
      paid_amount: {
              required:true,
                      rexp: ^[1-9]\d*(\.\d+)?$
      },

   }
     },

 messages: {
             paid_amount: {
                      required: "Enter Paid Amount",
              rexp:"Decimal Numbers Only"
    },  

     }
});

回答by dSquared

You can use the number validation method found here

您可以使用此处找到的数字验证方法

From the docs:

从文档:

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

In your case:

在你的情况下:

rules: {
    paid_amount: {
        required:true,
        number: true
    }
},
messages: {
    paid_amount: {
        required: "Enter Paid Amount",
        number: "Decimal Numbers Only"
    }
}

回答by black_belt

I'm not familiar with jquery validator plugin, sorry but your regular expression is valid.

我不熟悉 jquery 验证器插件,抱歉,您的正则表达式有效。

another approach would be

另一种方法是

var reg = "/^[1-9]\d*(\.\d+)?$/"; //reg pattern<br/>
if(reg.test("1.23"))//validate
{
 //do something <br/>
}

回答by RN Kushwaha

jQuery validator also supports decimal validation using range method.

jQuery 验证器还支持使用范围方法的十进制验证。

factor:
      {
        required: true,
        range:[0.08,20.09]  
      },

Read more hereand demohere.

在此处阅读更多信息并在此处进行演示

回答by merlincita_pj

Your problem is with the method 'rexg'. You should use 'pattern'. Example:

您的问题出在“rexg”方法上。你应该使用“模式”。例子:

paid_amount: {
     required:true,
     pattern: ^[1-9]\d*(\.\d+)?$
}

回答by Robert Niestroj

Use the jQuery isNumeric function: http://api.jquery.com/jQuery.isNumeric/

使用 jQuery isNumeric 函数:http: //api.jquery.com/jQuery.isNumeric/