Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  135] [ 1]  / answers: 1 / hits: 17781  / 11 Years ago, fri, january 10, 2014, 12:00:00

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, '');


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, '');

More From » regex

 Answers
11

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


[#73253] Thursday, January 9, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darrell

Total Points: 109
Total Questions: 113
Total Answers: 113

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
darrell questions
Mon, May 9, 22, 00:00, 2 Years ago
Sat, Mar 19, 22, 00:00, 2 Years ago
Sat, Oct 10, 20, 00:00, 4 Years ago
;