Reputation: 9407
I'm trying to validate Usernames with the following rules via RegExp
:
[a-z0-9-]
also.So a username like -username
, username-
or user---name
they should be all invalid, while a username like user-name
or my-user-name
should be still recognized as a valid username.
Currently I'm doing that via two RegExp like this: jsFiddle
var a = new RegExp("^([^-][a-z0-9][a-z0-9-]+[a-z0-9][^-])$", "i");
var b = new RegExp("-[-]+", "i");
var username = "some-one";
if ( a.test(username) && !b.test(username) ) {
alert(username.match(a)[1]);
} else {
alert('error');
}
The above code works perfectly fine, however I'm wondering if there is any way to combine these two RegExp in one. The reason is not neither performance nor cleaner code. I just want to improve my RegEx-ing skills as I've tried whatever I knew within the past few days, but with no success.
Update
Actually this ^([^-][a-z0-9][a-z0-9-]+[a-z0-9][^-])$
should be this ^([a-z0-9][a-z0-9-]+[a-z0-9])$
. I don't know why I put them there! jsFiddle
Upvotes: 1
Views: 73
Reputation: 1422
Check it on http://jsfiddle.net/Vv7ma/1/
var a = new RegExp("(^-|[-]{2}|-$)", "i");
var username = "some-one";
if (! a.test(username)) {
alert(username);
} else {
alert('error');
}
If '-' in front, error.
If '-' in end, error.
If '-' more than two in a row, error.
Final answer on http://jsfiddle.net/Vv7ma/3/ which fulfill (It should allows only [a-z0-9-] also.)
var a = new RegExp("^([a-z0-9]+-)+[a-z0-9]+$", "i");
var username = "some-one";
if (a.test(username)) {
alert(username);
} else {
alert('error');
}
Upvotes: 3