How can I restrict input to a text-box so that it accepts only numbers and the decimal point?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.
It's not perfect, but might give some ideas.
Allows:
11 11 .245 (in controller formatted on blur to 1111.245)
11,44
-123.123
-1 014
0123 (formatted on blur to 123)
doesn't allow:
!@#$/*
abc
11.11.1
11,11.1
.42
I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.
See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.
Here is the working code.
All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like
ctrl+c
,Pos1
etc.I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.
The
oninput
event is triggered just after something was changed in the text area and before being rendered.You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.
Starting from @rebisco answer :
Allows only this format : 123123123[.121213]
Demo here demo
Best and working solution with Pure-Javascript sample Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/