admin管理员组文章数量:1327843
I'm trying to validate a string with regex in javascript. The string can have:
- word characters
- parentheses
- spaces
- hyphens (-)
- 3 to 50 length
Here's my attempt:
function validate(value, regex) {
return value.toString().match(regex);
}
validate(someString, '^[\w\s/-/(/)]{3,50}$');
I'm trying to validate a string with regex in javascript. The string can have:
- word characters
- parentheses
- spaces
- hyphens (-)
- 3 to 50 length
Here's my attempt:
function validate(value, regex) {
return value.toString().match(regex);
}
validate(someString, '^[\w\s/-/(/)]{3,50}$');
Share
Improve this question
asked Apr 8, 2013 at 15:27
bflemi3bflemi3
6,79021 gold badges95 silver badges158 bronze badges
7
-
2
The escape character in regular expressions is
\
, not/
. And since you are using a string, you have to escape the\
themselves (or make your life easy and use a regex literal). – Felix Kling Commented Apr 8, 2013 at 15:30 - Yes, your current regex works fine if you use the correct escape felix mentioned – Smern Commented Apr 8, 2013 at 15:31
-
You are aware that word character as defined by
\w
includesA-Za-z0-9
and underscore_
, right? – nhahtdh Commented Apr 8, 2013 at 15:31 -
1
Inside square brackets you don't need to escape
-
,(
,)
etc. – anubhava Commented Apr 8, 2013 at 15:32 -
1
@anubhava: For
(
and)
you are right, but whether or not to escape-
depends on its position in the character class. – Felix Kling Commented Apr 8, 2013 at 15:33
1 Answer
Reset to default 6Write your validator like this
function validate(value, re) {
return re.test(value.toString());
}
And use this regex
/^[\w() -]{3,50}$/
Some tests
// spaces
validate("hello world yay spaces", /^[\w() -]{3,50}$/);
true
// too short
validate("ab", /^[\w() -]{3,50}$/);
false
// too long
validate("this is just too long we need it to be shorter than this, ok?", /^[\w() -]{3,50}$/);
false
// invalid characters
validate("you're not allowed to use crazy $ymbols", /^[\w() -]{3,50}$/);
false
// parentheses are ok
validate("(but you can use parentheses)", /^[\w() -]{3,50}$/);
true
// and hyphens too
validate("- and hyphens too", /^[\w() -]{3,50}$/);
true
本文标签:
版权声明:本文标题:javascript - Regex to allow word characters, parentheses, spaces and hyphen - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742214731a2434359.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论