Anirudh Rautela
Anirudh Rautela

Reputation: 113

Regex for not allowing consecutive dots or underscores

I have a Regex which allows only alpha numeric characters along with dot (.) and underscore (_)

It does not allow consecutive underscores but it allows consecutive dots. Can anyone please guide me through this problem. I don't want consecutive dots or underscores. Below is the JavaScript function

function checkLogin() {
  var login = $("#user_login").val();
  var regex = new RegExp("^(?!.*__.*)[a-zA-Z0-9_.]+$");
  var flag = true;
  if (regex.test(login)) {
    $('#valid_character_error').css("display","none");
  } 
  else  {
    $('#valid_character_error').css("display","block");
    flag = false;
  }
  return flag;
}

Upvotes: 2

Views: 10286

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

Just include the pattern which matches two dots inside the negative lookahead.

var regex = new RegExp("^(?!.*(?:__|\\.\\.))[a-zA-Z0-9_.]+$");

[a-zA-Z0-9_.]+ would be written as [\w.]

Update:

var regex = new RegExp("^(?!.*?[._]{2})[a-zA-Z0-9_.]+$");

DEMO

Upvotes: 7

nhahtdh
nhahtdh

Reputation: 56829

If you don't want __ or .. or ._ sequences to appear in your string, then this regex should work:

var regex = /^[a-zA-Z0-9]+([._][a-zA-Z0-9]+)*$/;

The regex above also reject strings that start or end with . or _. If you want to allow them:

var regex = /^[._]?[a-zA-Z0-9]+([._][a-zA-Z0-9]+)*[._]?$/;

Upvotes: 4

6502
6502

Reputation: 114609

This should do it

/^([^._]|[.](?=[^.]|$)|_(?=[^_]|$))*$/

Meaning:

  • ^(...)*$ the whole string is zero-or-more of...
  • [^._] a char but not a dot or an underscore
  • | or
  • [.](?=[^.]|$) a dot, followed by a different char or by the end of the string (but don't "use" that char)
  • | or
  • _(?=[^_]|$) an underscore, followed by a different char or by the end of the string (but don't "use" that char)

In other words you are looking for a sequence of either:

  • "regular" chars
  • dots not followed by dots
  • underscores not followed by underscores

Upvotes: 4

Related Questions