jqueryEnthusiast
jqueryEnthusiast

Reputation: 155

jquery validation issue

I am trying to match strings that contain 4 characters separated by |

Works fine in java when I use "(\\w{1,4})(\\|(\\w{1,4}))*"

When I use same pattern in jquery it does not match:

$.validator.addMethod("nameId",function(value,element){
return this.optional(element) || /^(\\w{1,4})(\\|(\\w{1,4}))*$/i.test(value);
},"Please enter valid input.");

Can anybody let me know how to do this in jquery.

Thanks!

Upvotes: 0

Views: 142

Answers (4)

axelarge
axelarge

Reputation: 967

Regexes in Javascript are first-class, not a string, so you don't need to double the backslashes (this results in literal backslashes).

Try this instead

/^(\w{1,4})(\|(\w{1,4}))*$/i

Edit: This is not directly related to the question, but some other improvements for this regex:

  • since you are only testing for a match and not using it, you should probably use non-capturing parentheses
  • the parentheses around \w and the repetition are not needed

Applying these changes would result in the slightly faster (and in my opinion more readable)

/^\w{1,4}(?:\|\w{1,4})*$/i

I created a quick comparison here: http://jsperf.com/capturing-vs-non-capturing-regex-parentheses

Upvotes: 1

Cfreak
Cfreak

Reputation: 19309

Use a single \ as the escape character:

/^(\w{1,4})(\|(\w{1,4}))*$/i

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816262

The double backslash is needed to create a literal backslash in the string. By itself, the backslash is treated as escape character inside a string. In order to create a literal \, you need to escape it \\.

As you have a regex literal in JS and not a string, you don't need to escape it:

/^(\w{1,4})(\|(\w{1,4}))*$/

Upvotes: 2

sdleihssirhc
sdleihssirhc

Reputation: 42496

My guess is because you include the double backslashes. If you change \\w to \w and etc., does that fix the problem?

Upvotes: 1

Related Questions