jQuery jquery中的正数验证

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

Positive number validation in jquery

jqueryvalidation

提问by Nazmul Hasan

I have used an expression for validating a positive number as follows:

我使用了一个表达式来验证正数,如下所示:

^\d*\.{0,1}\d+$

when I give it an input of -23, it will mark input as negative, but when I give it an input of +23, it will mark it as invalid number!

当我给它输入 -23 时,它会将输入标记为负数,但是当我给它输入 +23 时,它会将其标记为无效数字!

what is the problem?

问题是什么?

Can anyone give a solution that With +23 it will return (positive)?

谁能给出一个解决方案,+23 它将返回(正)?

回答by CMS

Have you considered to use anything beside regular expressions?

你有没有考虑过使用正则表达式之外的任何东西?

If you are using the jQuery Validation Pluginyou could create a custom validation method using the Validator/addMethodfunction:

如果您使用jQuery 验证插件,您可以使用Validator/addMethod函数创建自定义验证方法:

$.validator.addMethod('positiveNumber',
    function (value) { 
        return Number(value) > 0;
    }, 'Enter a positive number.');


Edit:Since you want only regular expressions, try this one:

编辑:因为你只想要正则表达式,试试这个:

^\+?[0-9]*\.?[0-9]+$

Explanation:

解释:

  • Begin of string (^)
  • Optional + sign (\+?)
  • The number integer part ([0-9]*)
  • An optional dot (\.?)
  • Optional floating point part ([0-9]+)
  • End of string ($)
  • 字符串开头 ( ^)
  • 可选 + 符号 ( \+?)
  • 数字整数部分 ( [0-9]*)
  • 一个可选的点 ( \.?)
  • 可选的浮点部分 ( [0-9]+)
  • 字符串结尾 ( $)

回答by Massimo

Or simply use: min: 0.01.
For example for money

或者简单地使用:min: 0.01
例如为了钱

回答by Md. Nahidul Alam Chowdhury

Easiest way is

最简单的方法是

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

ref : digits method | jQuery Validation Plugin --> https://jqueryvalidation.org/digits-method/

参考:数字方法| jQuery 验证插件 --> https://jqueryvalidation.org/digits-method/

回答by amber

Since I'm looking for something similar, this will test for a positive, non-zero value with an optional leading plus (+) sign.

由于我正在寻找类似的东西,这将测试一个带有可选前导加号 (+) 的非零正值。

^\+?[1-9][0-9]*$

This does not match decimal places nor does it match leading zeros.

这不匹配小数位,也不匹配前导零。

回答by Jeff Meatball Yang

^\+?\d*.{0,1}\d+$

Gets you the ability to put a "+" in front of the number.

使您能够在数字前放置“+”。

回答by Martin Jansen

If you insist on using a regular expression, please make sure that you also capture numbers with exponents and that you allow numbers of the form .42, which is the same as 0.42.

如果您坚持使用正则表达式,请确保您还捕获带指数的数字,并且您允许 0.42 形式的数字,这与 0.42 相同。

^+?\d*.?\d+([eE]+?\d+)?$

^+?\d*.?\d+([eE]+?\d+)?$

should to the trick.

应该诀窍。

回答by Emre Erkan

ok, try this;

好的,试试这个;

\+?\d*\.?\d+\b