简体   繁体   中英

Regex for negative and positive numbers

I need a regex for an input field to allow negative and positive numbers and no alphabet/special characters. I have seen other people achieve this but they allow the minus sign at any point in the string whereas I only want to allow the minus sign at the beginning of the string.

Note: I want to allow the user to use the arrow, del, home keys etc.

This the regex to get positive and negative numbers :

^-?\d+$

If you want decimal numbers you can use this :

^-?\d+(\.\d{1,2})?$

The parameter {1,2} at the end is for precision of your decimal number.

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