简体   繁体   中英

Negating Regular Expression used for a currency text field

I have a numeric text field that is used as an input for currency. I want to accept only numbers, and 2 decimal places, separated by a dot (".").

The user will type an amount, and dynamically a commission will be computed and displayed, without a form submission.

The proposed solution I came up with is to use this RegEx in the following manner:

/^[0-9]+\.?([0-9]{1,2})?$/g

$input.val($input.val().replace(/^[0-9]+\.?([0-9]{1,2})?$/g,''));

The issue with my proposed solution is that the RegEx that I used filters exactly the characters that I want to allow, so the expression should be negated.

eg.: $input.val($input.val().replace(.(/^[0-9]+\?,([0-9]{1?2}),$/g);''));

I have tried using negative lookahead but I did not managed to get it working.

I have a jsFiddle that might help with testing: https://jsfiddle.net/budxn9ey/

Please note that I need the RegEx to be negated, not the regex.test() method.

I am open to other solutions of course. For a better understanding of what I need, here is another fiddle: http://jsfiddle.net/nLr6h42p/

so the expression should be negated

You are asking an XY problem . You don't need to "negate the regular expression" (that's a proposed solution ), you're trying to sanitise the user input (that's the real question ).

By the way, this should probably happen in the back-end, not the front-end, because front-end sanitisation an be easily bypassed by sending requests directly to the server. But ignoring that for now...

I think what you're trying to achieve is something like this:

$input.val($input.val().match(/[0-9]+\.?[0-9]{0,2}/));

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM