使用jQuery将文本框输入限制为给定的正则表达式 [英] Restricting text box inputs to a given regexp using jQuery
问题描述
请考虑以下文本框:
<input type="text" name="quantity" id="quantity_field" />
使用jQuery我想将有效输入的集合限制在 quantity_field
由以下正则表达式:
Using jQuery I want to restrict the set of valid inputs into quantity_field
by the following regexp:
<script>
var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>
更具体地说,我想让浏览器丢弃输入 quantity_field <的任何字符/ code>会使文本字段的值不符合给定的正则表达式。 (当然也会在服务器端进行相应的检查。)
More specifically I want to make the browser discard any characters entered into quantity_field
that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)
示例:
- 如果用户输入foo 234,则只会在文本框中输入234。
- 如果用户输入001230,则只会输入1230在文本框中输入。
- 如果用户键入foo1bar,则只会在文本框中输入1。
问题:使用jQuery实现此目的的最简单方法是什么?
推荐答案
jQuery Constrain插件允许对文本框施加灵活约束并接受正则表达式。请参阅此演示。
jQuery Constrain plugin allows "flexible constraints to be imposed on text boxes" and accepts regular expressions. See this demo.
这篇关于使用jQuery将文本框输入限制为给定的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!