繁体   English   中英

正则表达式允许单词字符、括号、空格和连字符

[英]Regex to allow word characters, parentheses, spaces and hyphen

我正在尝试在 javascript 中使用正则表达式验证字符串。 字符串可以有:

  • 单词字符
  • 括号
  • 空间
  • 连字符 (-)
  • 3到50长度

这是我的尝试:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM