[英]Regex to allow word characters, parentheses, spaces and hyphen
我正在尝试在 javascript 中使用正则表达式验证字符串。 字符串可以有:
这是我的尝试:
function validate(value, regex) {
return value.toString().match(regex);
}
validate(someString, '^[\w\s/-/(/)]{3,50}$');
像这样写你的验证器
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.