I'm writing a mobile website and I would like the user to be able to login via username or phone number. I think the easist way to validate their response it to not allow them to signup using a phone number as their user name.
The problem is that I'll need to check if the input of the username field is JUST a 10 or 11 digit number. This is where my inexperance in regex comes to my disadvantage. I'm hoping to try something like
function do_reg($text, $regex)
{
if (preg_match($regex, $text)) {
return TRUE;
}
else {
return FALSE;
}
}
$username = $_POST['username'];
if(do_reg($username, '[0-9]{10,11}')){
die('cannot use a 10 or 11 digit number as a username');
}
The above regex is matching all numbers that are 10-11 digits long. I think maybe I need a way to say if the ONLY thing in the user input field is a 10-11 digit number get mad otherwise release the butterflies and rainbows.
EDIT: For the record I decided to make sure the username wasn't JUST a number. Thought this would be simpler and I didn't like the idea of having people use numbers as logins.
So I ended up with
if (!empty($username) && preg_match('/^\d+$/', $username )) {
die('username cannot be a number');
}
Thanks for the help all.
You are almost correct, except PCRE in PHP requires delimiters, and probably some anchors to make sure the field consists only of numbers.
if(do_reg($username, '/^\d{10,11}$/')){
// ^^ ^^
And probably use \d instead of [0-9].
(BTW, you should just call preg_match directly:
if (!preg_match('/^\d{10,11}$/', $username)) {
release('bufferflies', 'rainbows');
}
You need to anchor the regex to match the entire string: ^[0-9]{10,11}$.
^ matches the beginning of a string; $ matches the end.
Limit usernames to only 10 characters and require there username to start with a letter. How would a user write a 10 digit phone number as their username if they are required to enter in at least 1 alpha character (since phone numbers can't start with a 0/o or a 1/l)? (Heck I would require at least 3 alpha chars just to be safe).
When your app gets bigger then you can allow for longer usernames and take into account some of these issues:
Do not use ^ or $ signs if you are only testing the username: if(do_reg($username, '/^\d{10,11}$/')){
The reason I say this is anyone could defeat that by placing a letter in their username, a1235551212
instead use this:
if(do_reg($username, '/\d{10,11}/')){ because that will flag a1235551212d
Also, importantly, remember, that all of these regular expressions are only checking for numbers, there's nothing to stop a user from doing the following: ltwo3for5six7890. Unless of course you limit the username size.
You just should include start and end of the string in the regex
^[0-9]{10,11}$
Related
So I am trying to determine if someone is using a temporary email made by our system. If a user tries to login with a social account (Twitter / Facebook) and they decline access to email I generate an email for our system which is AccountID#facebook.com or AccountID#twitter.com so an example would be 123456789#facebook.com. This is a temporary email until a user enters a real email. I am trying to compare this using regex.
if (preg_match("/^[0-9]#twitter.com/", Auth::user()->email, $matches)) {
}
However I think my regex is incorrect. How would one check if the format of a string is N Number of digits followed by #twitter.com or #facebook.com
How would one check if the format of a string is N Number of digits followed by #twitter.com or #facebook.com
You can use this regex:
'/^\d+#(?:facebook|twitter)\.com$/'
You are using ^[0-9]# which will allow for only single digit at start. Besides DOT is a special character in regex that needs to be escaped. Also note use of end anchor $ in your anchor to avoid matching unwanted input.
You forget to set ID as MULTIPLE number:
if (preg_match("/^[0-9]+#(twitter|facebook)\.com/", Auth::user()->email, $matches))
{
//Your code here
}
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.
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_]))?)
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:
The length must be between 3 and 30 characters.
The accepted characters are like you said: a-z A-Z 0-9 dot(.) underline(_).
It's not allowed to have two or more consecutive dots in a row.
It's not allowed to start or end the username with a dot.
Putting all of that together will result in the following regex:
^[\w](?!.*?\.{2})[\w.]{1,28}[\w]$
Try it out here with examples!
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.
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
Okay so my edit was rejected because i should have posted it as an answer or comment so
if(!empty($instaUsername) && !preg_match("/([A-Za-z._])\w+/", $instaUsername)) {
throw new Exception ("Your name Instagram is incorrect");
}
i use this pattern
if(empty($instaUsername) or preg_match("/[a-z|A-Z|0-9|\.|\_]+$/", $instaUsername)==false) {
throw new Exception ("Your name Instagram is incorrect");
}
Reg
Useful regex
(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$
I'm using this for a password that needs to be 8-20 chars long, only numbers, letters and !##$% symbols:
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8, 20}$/', $_POST['password'])) {
$errors[] = true;
$_SESSION['error'] .= '<div class="messages status_red">Password must be 8-20 long, A-Z, 0-9, !##$% only.</div>';
}
However no matter if I meet the criteria or not I still return an error.
I don't see any error_reporting messages either.
Any idea what could be the reason for this?
The problem is the space in {8, 20}, which keeps it from being recognized as a {min,max} quantifier. But I don't know why you're complicating things with positive lookahead etc; something as simple as this should do the trick:
preg_match('/^[A-Za-z0-9!##$%]{8,20}$/', $_POST['password'])
EDITED TO ADD: It would be better security practice to allow any character at all in the password. If they can type it, let them use it - and it's on you to be able to process it without running afoul of SQL injection or similar. (You don't store passwords in your database anyway, right? Right.)
If you want to require a certain amount of character diversity in order to encourage stronger passwords - for instance, require at least one each of letter, number, and neither - then you can do something like this. Here, the use of lookahead means the letter, number, and neither-of-the-above can occur in any order in the password:
preg_match('/(?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])/', $_POST['password'])
You could try to get the length requirements into the regex, too, but I would just check the length separately - and here again, I would have a minimum, but no maximum. (Since passwords should never be stored, but only checksummed, longer passwords shouldn't incur any additional storage overhead. But if you do run into a situation where you need to limit the length for some reason, try to pick a limit in the hundreds-of-characters range rather than the tens-of-characters range.)
Don't put a space in {8, 20}. It should just be {8,20}.
A user enters a password, say 'tomorrow1234'. I'm aware that I can split it into an array with str_split, but after that, I want to go through each value and search them for things such as capitalization, number, or white space.
How would I go about doing this?
This is an old standby function I use to valiate password complexity. It requires that the password contains upper and lowercase letters, as well as non-alpha characters. Length checks are trivial and are handled elsewhere.
$req_regex = array(
'/[A-Z]/', //uppercase
'/[a-z]/', //lowercase
'/[^A-Za-z]/' //non-alpha
);
foreach($req_regex as $regex) {
if( !preg_match($regex, $password) ) {
return NULL;
}
}
I use the array and a loop so it's easy to add/remove conditions if necessary.
Sounds like your trying to verify password strength.
Check out this web page, your solution would be pretty complex to write a specific answer for, but you can use regex to check for things like capitalization, symbols and digits. This page has several examples you could modify for your needs.
http://www.cafewebmaster.com/check-password-strength-safety-php-and-regex
This is what I would use:
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
Checks for 1 letter, 1 number, 1 special character and at least 8 characters long.
Alright, so I want the user to be able to enter every character from A-Z and every number from 0-9, but I don't want them entering "special characters".
Code:
if (preg_match("/^[a-zA-Z0-9]$/", $user_name)) {
#Stuff
}
How is it possible for it to check all of the characters given, and then check if those were matched? I've tried preg_match_all(), but I didn't honestly understand much of it.
Like if a user entered "FaiL65Mal", I want it to allow it and move on. But if they enter "Fail{]^7(,", I want it to appear with an error.
You just need a quantifier in your regex:
Zero or more characters *:
/^[a-zA-Z0-9]*$/
One or more characters +:
/^[a-zA-Z0-9]+$/
Your regex as is will only match a string with exactly one character that is either a letter or number. You want one of the above options for zero or more or one or more, depending on if you want to allow or reject the empty string.
Your regular expression needs to be changed to
/^[a-zA-Z0-9]{1,8}$/
For usernames between 1 and 8 characters. Just adjust the 8 to the appropriate number and perhaps the 1.
Currently your expression matches one character
Please keep in mid that preg_match() and other preg_*() functions aren't reliable because they return either 0 or false on fail, so a simple if won't throw on error.
Consider using T-Regx:
if (pattern(('^[a-zA-Z0-9]{1,8}$')->matches($input))
{
// Matches! :)
}