2013-04-08 151 views
1

我试图用JavaScript中的正则表达式验证字符串。该字符串可以有:正则表达式允许单词字符,括号,空格和连字符

  • 字字符
  • 括号
  • 空间
  • 连字符( - )
  • 3至50长度

这里是我的尝试:

function validate(value, regex) { 
    return value.toString().match(regex); 
} 

validate(someString, '^[\w\s/-/(/)]{3,50}$'); 
+2

转义字符在正则表达式是''\''不''/' '。而且,由于您使用的是字符串,因此您必须自行转义''''(或让您的生活变得轻松并使用正则表达式)。 – 2013-04-08 15:30:40

+0

是的,如果你使用正确的escape felix,你当前的正则表达式工作正常 – smerny 2013-04-08 15:31:50

+0

你知道'\ w'定义的单词字符包括'A-Za-z0-9'和下划线'_',对吧? – nhahtdh 2013-04-08 15:31:57

回答

5

写您的验证这样

function validate(value, re) { 
    return re.test(value.toString()); 
} 

,并使用此正则表达式

/^[\w() -]{3,50}$/ 

一些测试

// 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 
+2

此外,如果你只是想验证,'RegExp.test()'可能是一个更好的选择,然后'String.match()'。 – 2013-04-08 15:33:46

+0

在这个答案中,你看到'str#match'?我在'validate'方法中使用're#test'。 – 2013-04-08 19:26:24

+0

这是在问题:'返回value.toString()。匹配(正则表达式);'。 – 2013-04-08 20:37:46

相关问题