文本框的正则表达式,仅允许某些符号

时间:2014-03-12 06:07:13

标签: javascript regex

我有一个文本框。在我的文本框中,我应该输入年龄范围作为数字。

在我的文本框中,年龄范围应仅允许任何一个符号作为     -,>=,<=,>,<only number.

Examples are 30-40,>30,>=30,<30,<=30,30

只允许使用这些符号。     我必须验证此文本框,请为此文本框提供正则表达式。

2 个答案:

答案 0 :(得分:1)

您不需要javascript,html5表单元素可以使用pattern属性进行验证。这是一个示例标记:

<input type="text" name="agerange" pattern="[\-<>=\d+]+">

阅读about html5 forms at html5rocks

第一个正则表达式只检查有效字符:

^[\-<>=\d+]+$

你可以测试here,他们在那里给出了一个很好的图表。 打破正则表达式:

^     means: at the start of the string
[ ]   the square brackets give a list of characters we want to match
[ ]+  the plus at the end of the square brackets are a loop, meaning "one or more of these"
$     means: at the end of the string
\-    the minus sign needs a backslash to escape it
<     just stands for itself
>     just stands for itself
=     just stands for itself
\d    matches any digit

所以用英语概括:这个正则表达式将匹配任何字符串 包含任何顺序的减号,小于号,大于号,等号和/或数字。并且该字符串可能不包含任何其他内容。

要正确使用语法

^(?:\d+-|>=?|<=?|=)?\d+$

在线测试here

这有点难以解释,来自debggex的图应该真的有用:

diagam for regular experession

从小部分开始:

X+     a plus sign after something means "one or more of these", so
\d+-   means one or more numbers followed by a minus sign
X?     a question mark after something means "zero or one of these", so
=?     means either an equal sign or nothing at all, so 
>=?    means a greater-than sign followed by an optional equal-sign
>=?    means a greater-than sign followed by an optional equal-sign

如果你缩小一点就可以看到我们刚刚讨论的片段是分开的 通过管道标志:

\d+-|>=?|<=?|=     so this is either digigs followed by a minus,
                                  or  greater-than, possibly followed by an equal sign
                                  or  less-than, possibly followed by an equal sign
                                  or  just an equal sign 

这四种选择包含在一个特殊的括号中:

(?:X)        means: group this together, but do not save the results

我们也可以使用

(X)          which will wave the matched string into a special variable.

这应该给你所有的点点滴滴来理解整个模式。

答案 1 :(得分:0)

这将有效:

/^((\d+)|(\d+\-\d+)|((>|(>=)|<|(<=))\d+))$/

bjelli:您的模式将匹配3>30