简体   繁体   中英

How to make an input box to accept positive and negative decimal values?

How can I make an input box to accept only one - sign OR one + sign AND one decimal point with numbers?

I tried `preventDefault(); to block other characters by following code:

$('.pndecimal').on('keypress keyup blur', function(e){
         if(e.which< 48 && e.which > 57)
         { 
            e.preventDefault();
         }
    });

I'm not able to allow these because they are out of range of ASCII codes of numbers (e.which<48 & e.which >57)

Use regular expression validation, if it passes take the value or else show error.

eg: /(-|\\+)+[0-9]+\\.[0-9]+/g

valid inputs: +9.0, -9.7, +78.9, -10.0

If you want to have more than one number after decimal point than use this pattern(this patterns also allow inputs like -99/,++,--)

eg: /(-|\\+)+[0-9]+\\.[0-9]+/g

valid inputs: +91.42, +1.809, -9.0

If you want to restrict to 2 integer numbers,2 decimal numbers,any one sign use the following:

RegExp(/(-|\+)+[0-9]+\.[0-9]+/g)

<input type="text" maxlength="4">

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