Javascript/Jquery验证按键/击键时的十进制输入 [英] Javascript/Jquery validating decimal input on keypress/keydown
问题描述
我正试图找到一种方法来验证按键时的文本输入,我只允许在我的文本输入中包含数字,包括小数.
I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
我正在使用使用jQuery.keydown的方法,并检查键是什么,如果键不在允许列表中,则使用event.preventDefault().但是从那以后,我读到密钥在整个浏览器中并不一致,并且我还担心不同的操作系统.
I was taking the approach of using jQuery.keydown, and checking what the key was and using event.preventDefault() if the key was not in the allowed list. But since then I've read that keys aren't consistent throughout browsers and I'm also worries about different OS's.
我遇到了这个问题,但是我不太会使用正则表达式,也不确定这是否适合我的需求: jquery-验证按键上的字符吗?
I've come across this question but I'm not fluent in regex and not sure whether this would suit my needs: jquery - validate characters on keypress?
通过这种方法,由于键入时会检查正则表达式,因此当键入00.时,期望00.00的正则表达式将停止用户.
With that approach a regex that expects 00.00 would stop the user when 00. is typed in since the regex is checked upon key up.
谢谢
推荐答案
您不应依赖按键事件,因为这意味着如果用户执行右键单击->粘贴,验证将失败.包含无效字符.
You should not rely on key events as that would mean the validation would fail if the user does a right-click -> paste with invalid characters.
您应该做的是使用zurb的textchanged
事件-无论输入的方式如何(键,粘贴,拖放等),该事件都会准确触发
What you should instead do is use something like zurb's textchanged
event - which will accurately trigger regardless of the mode of input (key, paste, drag and drop, whatever)
http://www.zurb.com/playground/jquery-文字更改自定义事件
在textchanged
处理程序内部,您可以放入适当的正则表达式来处理小数.
Inside your textchanged
handler, you can put in the appropriate regex to deal with decimals.
这篇关于Javascript/Jquery验证按键/击键时的十进制输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!