简体   繁体   中英

Detect multiple dashes

I'm trying to validate Usernames with the following rules via RegExp :

  1. Avoid leading and following dashes
  2. Avoid multiple dashes
  3. Update: It should allows only [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

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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