Username may contain lowercase characters and numbers - php

I want to allow lowercase characters and numbers in username field.
But with following conditions...
Only numbers as username NOT allowed (e.g. only mobile number)
Only lowercase characters allowed (e.g. without any number in username)
Lowercase characters + numbers allowed (e.g. combination of lowercase and numbers)
Minimum length 8 characters required
Maximum length 20 characters allowed
What php regex will do it ?
I tried with following, but it forces lowercase + numbers. Only lowercase username not allowing.
$username_pattern = '/^(?=.*[a-z])(?=.*[a-z])(?=.*\d)[a-z0-9]{8,20}$/';
I want only lowercase and/or lowercase+numbers ( min 8 and max 20 ) in username
Help appreciated.

You can simplify it to not allowing only digits
^(?!\d*$)[a-z0-9]{8,20}$
Explanation
^ Start of string
(?!\d*$) Negative lookahead, assert not only digits till end of string
[a-z0-9]{8,20} Match 8-20 times a char a-z or a digit 0-9
$ End of string
Regex demo | Php demo
$username_pattern = '/^(?!\d*$)[a-z0-9]{8,20}$/';
$userNames = [
"1a3b5678",
"1a3b5678abcd",
"12345678",
"1a3b5678abcddddddddddddddddddddddddddddddd",
"1a3B5678",
"a1"
];
foreach ($userNames as $userName) {
if (preg_match($username_pattern, $userName)) {
echo "Match - $userName" . PHP_EOL;
} else {
echo "No match - $userName" . PHP_EOL;
}
}
Output
Match - 1a3b5678
Match - 1a3b5678abcd
No match - 12345678
No match - 1a3b5678abcddddddddddddddddddddddddddddddd
No match - 1a3B5678
No match - a1

Related

Beginner PHP. Regular expression, excluding characters

I am trying to create a regex for my form that will accept lower case characters a-z, upper case A - Z and all numbers.
I have successfully included what needs to be accepted, but what I want to do is exclude the following characters $£*
The code I have so far is as follows:
if (!preg_match("/^[a-zA-Z0-9 ^$£* ]{1,20}$/", $webdata['familypa']))
Your pattern can be accurately/concisely written as:
~^[a-z\d]{1,20}$~i
if(!preg_match('~^[a-z\d]{1,20}$~i',$webdata['familypa'])){
echo 'familypa is not an alpha-numeric string or doesn\'t have a length of between 1 & 20 characters';
}else{
echo 'familypa is all good';
}
Or you can write a more verbose, non-regex method:
*The conditional checks for positive length, then length less than 21, then alpha-numeric.
if($len=strlen($webdata['familypa']) && $len<21 && ctype_alnum($webdata['familypa'])){
echo 'familypa is all good';
}else{
echo 'familypa is not an alpha-numeric string or doesn\'t have a length of between 1 & 20 characters';
}
The regex expression for accepting lower case characters a-z, upper case A - Z and all numbers (considering any number 0-9 ) is the following : regex:/^[a-zA-Z0-9]*$/

preg_match - to allow only one dash

I'm using preg_match and its working to allow; numbers, letters and dash. but i want to limit the dash to 1 only. i tried added {1} before and after the dash but its still allowing more than one. what am i doing wrong?
if (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
} else {
This is the code that i'm using.
Thanks
Make an extra test for the dash count to keep it simple.
if (!preg_match("/^[A-Za-z0-9\-]+$/", $username) || substr_count($username,'-') > 1) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
}
Since you seem to validate a string that can contain one or zero hyphens in an alphanumeric string, you may use a negative lookahead in your pattern to fail the match if 2 hyphens are found:
"/^(?![^-]*-[^-]*-)[A-Za-z0-9-]+$/D"
^^^^^^^^^^^^^^^^
Pattern details:
^ - start of a string
(?![^-]*-[^-]*-) - fail the match if there are 2 hyphens separated with 0+
chars other than -
[A-Za-z0-9-]+ - 1 or more alphanumeric chars or hyphens
$ - the very end of the string (since /D modifier is used).
See a regex demo (pattern modified to account for a multiline string input).
Note that if you want to disallow - to appear at the start/end of the string, and several consecutive -s, use a more straight-forward pattern:
"/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)?$/D"
where ^[A-Za-z0-9]+ will match 1+ alphanumeric chars at the start of the stirng, and (?:-[A-Za-z0-9]+)?$ will match 1 or 0 occurrences of a - followed with 1+ alphanumeric chars at the end of the string.
$username = "abc-edf-tru-ksk-5-ll-hr-foam-6-inch-queen-anroid-phone-stackoverflow-72-x-70-x-6290321_1";
This below code allow hypens(-) and underscore(_)
if(preg_match('/^[a-zA-Z0-9\-\_]+(-[a-zA-Z0-9\-\_]+)*$/', $username))
{
echo "The username you selected valid characters are hypens,underscores, letters and numbers.";
}
allow only hypen(-)
if(preg_match('/^[a-zA-Z0-9\-]+(-[a-zA-Z0-9\-]+)*$/'), $username))
{
echo "The username you selected valid characters are hypens(only), letters and numbers.";
}
allow only underscore(_)
if(preg_match('/^[a-zA-Z0-9\_]+(-[a-zA-Z0-9\_]+)*$/'), $username))
{
echo "The username you selected valid characters are underscores(only),underscores, letters and numbers.";
}
not allow hypens, underscores and symbols
if(preg_match('/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/'), $username))
{
echo "The username you selected valid characters are letters and numbers.";
}

php regular expression minimum and maximum length doesn't work as expected

I want to create a regular expression in PHP, which will allow to user to enter a phone number in either of the formats below.
345-234 898
345 234-898
235-123-456
548 812 346
The minimum length of number should be 7 and maximum length should be 12.
The problem is that, the regular expression doesn't care about the minimum and maximum length. I don't know what is the problem in it. Please help me to solve it. Here is the regular expression.
if (preg_match("/^([0-9]+((\s?|-?)[0-9]+)*){7,12}$/", $string)) {
echo "ok";
} else {
echo "not ok";
}
Thanks for reading my question. I will wait for responses.
You should use the start (^) and the end ($) sign on your pattern
$subject = "123456789";
$pattern = '/^[0-9]{7,9}$/i';
if(preg_match($pattern, $subject)){
echo 'matched';
}else{
echo 'not matched';
}
You can use preg_replace to strip out non-digit symbols and check length of resulting string.
$onlyDigits = preg_replace('/\\D/', '', $string);
$length = strlen($onlyDigits);
if ($length < 7 OR $length > 12)
echo "not ok";
else
echo "ok";
Simply do this:
if (preg_match("/^\d{3}[ -]\d{3}[ -]\d{3}$/", $string)) {
Here \d means any digits from 0-9. Also [ -] means either a space or a hyphen
You can check the length with a lookahead assertion (?=...) at the begining of the pattern:
/^(?=.{7,12}$)[0-9]+(?:[\s-]?[0-9]+)*$/
Breaking down your original regex, it can read like the following:
^ # start of input
(
[0-9]+ # any number, 1 or more times
(
(\s?|-?) # a space, or a dash.. maybe
[0-9]+ # any number, 1 or more times
)* # repeat group 0 or more times
)
{7,12} # repeat full group 7 to 12 times
$ # end of input
So, basically, you're allowing "any number, 1 or more times" followed by a group of "any number 1 or more times, 0 or more times" repeat "7 to 12 times" - which kind of kills your length check.
You could take a more restricted approach and write out each individual number block:
(
\d{3} # any 3 numbers
(?:[ ]+|-)? # any (optional) spaces or a hyphen
\d{3} # any 3 numbers
(?:[ ]+|-)? # any (optional) spaces or a hyphen
\d{3} # any 3 numbers
)
Simplified:
if (preg_match('/^(\d{3}(?:[ ]+|-)?\d{3}(?:[ ]+|-)?\d{3})$/', $string)) {
If you want to restrict the separators to be only a single space or a hyphen, you can update the regex to use [ -] instead of (?:[ ]+|-); if you want this to be "optional" (i.e. there can be no separator between number groups), add in a ? to the end of each.
if (preg_match('/^(\d{3}[ -]\d{3}[ -]\d{3})$/', $string)) {
may it help you out.
Validator::extend('price', function ($attribute, $value, $args) {
return preg_match('/^\d{0,8}(\.\d{1,2})?$/', $value);
});

PHP Regex start with a letter

How can I check if the input is C12345 ( Capital letter "C" followed by 5 numbers (total 6 digits)
I have this code
$val = "/^\d\d\d\d\d\d$/";
if (! preg_match($val, $source)) {
$error_msg .= "<p>your source must be 6 digits long</p>";
}
$secval = "/^\"C\"\d\d\d\d\d$/";
if (! preg_match($secval, $source)) {
$error_msg .= "<p>source must be 6 digits long and start with an "S"</p>";
}
try this
^[A-Z]\d{5}$
Single letter, A through Z followed by 5 digits
If the first letter must be C, use
^C\d{5}$
Use this regex:
^C\d{5}$
Debuggex Demo
If you want any other character, use the character set [A-Z], which means, any character from capital A to Z
^[A-Z]\d{5}$

PHP regex for password validation

I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.
A-Z
a-z
0-9 >= 2
special chars >= 2
string length >= 8
So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.
Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.
PHP CODE:
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
$special = preg_match('#[\W]{2,}#', $password);
$length = strlen($password) >= 8;
if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
$errorpw = 'Bad Password';
Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>
^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$
Add your special character set to last [...] in the above regex (I put there for now just -+%#).
Explanation:
^ - beginning of line/string
(?=.{8}) - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z]) - ...to ensure we have at least one uppercase char
(?=.*[a-z]) - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])
- ...to ensure we have at least three special chars
(characters other than letters and numbers)
[-+%#a-zA-Z\d]+ - combination of allowed characters
$ - end of line/string
((?=(.*\d){3,})(?=.*[a-z])(?=.*[A-Z])(?=(.*[!##$%^&]){3,}).{8,})
test$ABC5#8 is not valid because you ask more than 2 digits and spec symbols
A-Z
a-z
0-9 > 2
special chars > 2
string length >= 8
For matching length of string including special characters:
$result = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[\s\S]{6,16}$/', $string);
Answer explained: https://stackoverflow.com/a/46359397/5466401

Categories