JavaScript 用于带一个或不带点的有效正数和负数

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

JavaScript for valid positive and negative numbers with one or no dots

javascriptregexhtmlangularjs

提问by bbodenmiller

I am using a AngularJS directiveto only allow a user to enter numbers, decimals, and minus signs however I'd like to update it to allow only one dot and one negative sign at the beginning. The following is what I have now but it allows invalid inputs like --1:

我使用AngularJS 指令只允许用户输入数字、小数和减号,但是我想更新它以在开头只允许一个点和一个负号。以下是我现在所拥有的,但它允许无效输入,例如--1

val.replace( /[^0-9.-]+/g, '');

I need help fixing the RegEx to allow inputs like -1, .1, -.1, 0.1, and -0.1but not like --1, 1.1.1, 1-1, -., 1., 1.k, and k.

我需要帮助修复 RegEx 以允许诸如-1, .1, -.1, 之类的输入0.1-0.1但不能像--1, 1.1.1, 1-1, -., 1., 1.k, 和k

I managed to only allow one decimal with the following but have struggled with then allowing the negative sign only at the beginning:

我设法只允许一位小数,但一直在努力,然后只在开始时允许负号:

val.replace(/[^\d*[0-9]\.\d*[0-9]]/g, '');

回答by tenub

I think ^-?\d*\.?\d+$is the simplest solution that works with all test cases.

我认为^-?\d*\.?\d+$是适用于所有测试用例的最简单的解决方案。

回答by Beterraba

I have a similar directive, and I use this regex:

我有一个类似的指令,我使用这个正则表达式:

/^\-?\d+((\.|\,)\d+)?$/

/^\-?\d+((\.|\,)\d+)?$/.test("1.2.2") // false
/^\-?\d+((\.|\,)\d+)?$/.test("1.22")  // true
/^\-?\d+((\.|\,)\d+)?$/.test("-1")    // true
/^\-?\d+((\.|\,)\d+)?$/.test("--1")   // false

Change to

改成

/^\-?\d+((\.)\d+)?$/

to fail when the input has a comma instead of a dot.

当输入有逗号而不是点时失败。

回答by Edgar Villegas Alvarado

Your regex lacks of the 'starts with' ^and 'ends with' $operators:

您的正则表达式缺少“开始于”^和“结束于”$运算符:

Should be

应该

/^[^\d*[0-9]\.\d*[0-9]]$/g

Cheers

干杯

回答by Oleg

Try this:

试试这个:

/^-?[0-9]+(?:\.[0-9]+)?$/

回答by Casimir et Hippolyte

You can use this:

你可以使用这个:

/^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/

回答by Matt

This handles all your test cases:

这将处理您的所有测试用例:

/^-?\d*\.?\d+$/

Edited to notmatch 1.

编辑为匹配1.

To keep only the first instances of -and .:

只保留-and的第一个实例.

function r(m,a,b) { return a+b.replace(new RegExp('\'+a,'g'),''); }
"--1.2.3".replace(/(-)(.*)/g,r).replace(/(\.)(.*)/,r).replace(/[^-\.\d]/g,'')
// -1.23

回答by farvilain

I propose you something more readable

我建议你一些更具可读性的东西

function validateFloat(string){
    var floatString = parseFloat(value) +"";
    return (floatString !== string);
}

Ok for u?

对你好吗?