Reputation: 113
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
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_.]+$");
Upvotes: 7
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
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:
Upvotes: 4