I have register form and input of "instagram-username".
Instagram username can included only: a-z A-Z 0-9 dot(.) underline(_)
This is my code:
if(!empty($instaUsername) && preg_match("/([A-Za-z._])\w+/", $instaUsername)) {
throw new Exception ("Your name Instagram is incorrect");
}
When $instaUsername = "name.123"
or "name_123"
this give me the error.
How to make a regular expression according to the following requirements?
a-z A-Z 0-9 dot(.) underline(_)
I would love to have good tutorials on regex as comment.
Thus you want a regex what validates Instagram usernames? Well then, shall we first do some research on what the requirements actually are? Okay let's start!
...
Well it seems like Instagram doesn't really speak out about the requirements of a valid username. So I made an account and checked what usernames it accepts and what usernames are rejected to get a sense of the requirements. The requirements I found are as following:
a-z A-Z 0-9 dot(.) underline(_)
.Putting all of that together will result in the following regex:
^[\w](?!.*?\.{2})[\w.]{1,28}[\w]$
Try it out here with examples!
jstassen has a good write up on insta user names:
(?:^|[^\w])(?:@)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)
I found a lot of the answers here way too complicated and didn't account for a username being used in a sentence (like hey @man... what's up?
), so I did my own
/@(?:[\w][\.]{0,1})*[\w]/
This says:
@
: Find an @ symbol (optional)([\w][\.]{0,1})+
: Find a word character (A-Z, 0-9, _) and up to 1 dot in a row, *
as many times as you like (e.g. allow @u.s.e.r.n.a.m.e
, but not @u..sername
)(?:
this before the above just means "don't actually create a capturing group for this"[\w]
end with a word character (i.e. don't allow a final dot, like @username.
should exclude the dot)If you want to limit the username to 30chars like IG does, then:
@(?:(?:[\w][\.]{0,1})*[\w]){1,29}
This just wraps everything in another non-capturing (?:
group and limits the total length to 29 chars
Moving forward from the comment section, this is what you want:
if(!empty($instaUsername) && preg_match('/^[a-zA-Z0-9._]+$/', $instaUsername)) {
throw new Exception ("Your name Instagram is incorrect");
}
This regex should work for you:
~^([a-z0-9._])+$~i
You can use anchors to match the start (^
) and the end $
of your input. And use the modifier i
for case-insensitivity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With