JavaScript,有效的带一个或多个点的正负数 [英] JavaScript for valid positive and negative numbers with one or no dots
问题描述
我正在使用 AngularJS指令仅允许用户输入数字,小数和减号,但是我d希望对其进行更新,以使其开头只能有一个点和一个负号.以下是我现在拥有的内容,但它允许使用--1
这样的无效输入:
I am using a AngularJS directive to 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
:
val.replace( /[^0-9.-]+/g, '');
我需要修复RegEx以便允许输入类似-1
,.1
,-.1
,0.1
和-0.1
的输入,但不能像--1
,1.1.1
,1-1
,1.
,1.k
和k
.
I need help fixing the RegEx to allow inputs like -1
, .1
, -.1
, 0.1
, and -0.1
but not like --1
, 1.1.1
, 1-1
, -.
, 1.
, 1.k
, and 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, '');
推荐答案
我认为^-?\d*\.?\d+$
是适用于所有测试用例的最简单解决方案.
I think ^-?\d*\.?\d+$
is the simplest solution that works with all test cases.
这篇关于JavaScript,有效的带一个或多个点的正负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!