1

I am not very good in Regular Expression, and can't seem to understand them quite well.

I am looking for a regular expression which will match and allow following strings for a username, with these conditions:

  • username can: start with a number or with a alphabetic letter
  • username can contain special chars: dots, dashes, underscores
  • username must be in this range: from 3 chars up to 32 chars.
  • alphanumeric characters in the username can be both: lowercase and uppercase
  • cannot contain empty spaces

Almost similar to Twitter's and Facebook username patterns.

Please help me. Thank you.

FWI: I have tried this: /^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/ - and this does not satisfy my conditions.

0

4 Answers 4

5

Try this one

^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$

this results in the php code

if (preg_match('~^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$~', $username) {
    //do something
}
0
2

Starts with digit or alphabetic

[a-zA-Z0-9]

can contain as above plus dots, dashes and underscores

[a-zA-Z0-9._-]

and all together

[a-zA-Z0-9][a-zA-Z0-9._-]{2, 31}
2

try this one this is working for me in every registration form

//username Validation
var usernameRegex = /^[a-zA-Z0-9\s\[\]\.\-#']*$/i;
var username=document.getElementById('username');
if(username.value==""){
document.getElementById('lblusername').innerHTML="Username Required!";
username.focus();
return false;
}   
else if(usernameRegex.test(username.value)== false) 
{
document.getElementById('lblusername').innerHTML="Allow Alphanumeric Only! (E.g Demo123)";
username.focus();
return false;
}
else
{
document.getElementById('lblusername').innerHTML="";
}   
1

Try this:

^[0-9a-zA-Z][0-9a-zA-Z\-\._]{2,31}$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.