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 includes A-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
 |  Show 2 more ments

1 Answer 1

Reset to default 6

Write 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

本文标签: