最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex for negative and positive numbers - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Dec 16, 2016 at 14:10 midda25midda25 1602 gold badges2 silver badges12 bronze badges 2
  • 4 [-+]?\d+ accepts one or more digits that may or may not have a plus + or minus - in front of them. I don't follow what you mean about arrow keys, that's not really something regex interacts with – Patrick Haugh Commented Dec 16, 2016 at 14:13
  • 0.125, -.4, 0xbabe, 1e-23, Infinity, ۸۹۸ etc - do you consider these to be "numbers"? – georg Commented Dec 16, 2016 at 14:51
Add a ment  | 

1 Answer 1

Reset to default 5

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.

发布评论

评论列表(0)

  1. 暂无评论