I am trying to validate if a new user account's password is matching these criterias:
Between 8-30 characters long
Contains at least 1 lowercase letter (a-z)
Contains at least 1 uppercase letter (A-Z)
Contains at least 1 of the following special characters: _-!#*#&
I have a function like this:
function validPassword($str) {
return preg_match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_-!#*#&])[A-Za-z\d_-!#*#&]{8,30}$", $str);
}
But I am getting an error. It should return "true" for this password for example: HelloWorld123!
But instead it is returning false. Any idea what may be wrong?
if (validPassword($password) == true) {
// good password
}
You forgot to escape '-', and delimiters...
function validPassword($str) {
return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$/", $str);
}
Your regex is having errors which is why there is no match in the first place.
Change your regex to this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$
Have a look at your regex in action here: https://regex101.com/r/ogPPeb/1
Related
Im trying to make a preg_match rule for user validation
to only allow a-z - A-Z - 0-9
and the characters _-=?!#:.,
without spaces
I already tried a lot of combinations but no one seems to work
This is what im trying to get:
if(preg_match('idk what to use here', 'Myusername#123?')) {
return true;
}
if(preg_match('idk what to use here', '$Hello')) {
return false;
}
if(preg_match('idk what to use here', 'Hello 123')) {
return false;
}
Anyone knows the regex for this?
Thanks :)
Use a class, but make sure to either escape the hyphen or put it as the last character, otherwise it signifies a range. Use ^ and $ to require that all input characters match the pattern:
$regex = "/^[A-Za-z0-9_=?!#:.,-]*$/";
var_dump(preg_match($regex, 'Myusername#123?'));
var_dump(preg_match($regex, '$Hello'));
var_dump(preg_match($regex, 'Hello 123'));
This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 6 years ago.
i have this function:
public static function encPasswordCheckFailed($password)
{
if (!preg_match('/[A-Z]+/', $password)){
return true;
}
if (!preg_match('/[a-z]+/', $password)){
return true;
}
if (!preg_match('/[0-9]+/', $password)){
return true;
}
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
return false;
}
and now i want to force the user to have at least 1 Uppercased Letter, 1 Lowercased Letter, 1 Number and 1 Specialcharacter.
I'm having the problem with this:
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
All other requirements work. I have only a problem with the specialcharacters.
Can someone tell me the correct pattern for these specialcharacters: !##$%^&*()-+<>
i've read some of the answers from here, here and here but they didn't help me further...
You may need to escape some special characters used by the Regex Engine. And by the way, you could as well do that in one Go as shown below. Quick-Test Here.
<?php
/*public static*/ function encPasswordCheckFailed($password) {
// THIS READS:
// IF THE PASSWORD DOES CONTAIN AN UPPER-CASE CHARACTER
// AND ALSO DOES CONTAIN A LOWER-CASE CHARACTER
// AND STILL DOES CONTAIN A NUMERIC CHARACTER
// AND EVEN MORE, DOES CONTAIN ANY OF THE SPECIFIED SPECIAL CHARACTERS
// RETURN FALSE OTHERWISE RETURN TRUE
if (preg_match('/[A-Z]+/', $password) && // CHECK FOR UPPERCASE CHARACTER
preg_match('/[a-z]+/', $password) && // AND CHECK FOR LOWERCASE CHARACTER
preg_match('/[0-9]+/', $password)&& // AND CHECK FOR NUMERIC CHARACTER
preg_match('/[\!##$%\^&\*\(\)\-\+<>]+/', $password) // AND CHECK FOR SPECIAL CHARACTER
) {
return false;
}
return true;
}
var_dump( encPasswordCheckFailed("abcd123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD1#23-") ); //<== boolean false
The dash/minus character is your issue, as when inside a character group, it denotes a character range.
You need to either:
Escape it with a backslash, so that it isn't treated as a special character:
/[!##$%^&*()\-+<>]+/
Or put it at the end of the pattern, so the PCRE engine knows it can't possibly denote a range:
/[!##$%^&*()+<>-]+/
Similarly, the caret (^) is also a special character, denoting negation when inside a character group, but because you didn't put it at the very first position inside the character group, the PCRE engine knows it has no special meaning in your case.
This will gonna work for special characters:
preg_match('/\[!##$%^&*\(\)\-+<>\]+/', $password);
If it's not working, look down:
OTHER ANSWERS:
preg_match php special characters (pmm's answer)
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.
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
}
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}
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="";
}
Try this:
^[0-9a-zA-Z][0-9a-zA-Z\-\._]{2,31}$
I made this function to check if the first character is a letter.
function isLetter($string) {
return preg_match('/^\s*[a-z,A-Z]/', $string) > 0;
}
However, if I check a sentence that starts with a coma (,) the functions returns true. What is the proper regex to check if the first letter is a-z or A-Z?
You just need to remove the comma:
'/^\s*[a-zA-Z]/'
A slightly cleaner way, in my opinion. Just makes the code a little more human readable.
function isLetter($string) {
return preg_match('/^[a-z]/i', trim($string));
}
This question already has answers here:
php validate integer
(7 answers)
Closed 9 years ago.
Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.
For example, any of the following values should be valid:
7
0
32
47534
The following SHOULD NOT be valid:
asdf
35/gdf
../34.
etc..
I'm using the following if statement to check for the positive integer value of "$original_stock".
if (preg_match("/^[0-9]$/", $original_stock))
{
$error .="Original stock must be numerical.";
}
Additionally, I have a price field which should be validated as either an int or a double.
If there's an easier alternative to using regex, that's okay too!
Thanks in advance :)
Try this regexp:
/^\d+$/
The issue with your existing regexp is that it only matches strings with exactly one digit.
As for validating an int or a double:
/^\d+\.?\d*$/
Note that that regexp requires that there be at least one digit.
Use:
/^[0-9]+$/
The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:
/^\d+$/
For floats, try something like:
/^\d+(\.\d{1,2})?/
This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)
To save yourself some headaches, you can also use the is_int and is_float functions.
Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:
if (!preg_match("/^\+$/", $original_stock)) {
// error
}
(note the !).
You may want to use the
is_int
Don't reinvent a wheel slower than an existing one, use a motorcycle: is_int.
#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
#Valid, do stuff
}
else {
#Invalid, do stuff
}
#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
if (!is_int($s)) {
$valid = false;
break;
}
}
if ($valid) {...}
else {...}
I just ran into this exact problem and solved it this way using the regex.
I think the problem is your caret ^.
/^[0-9]$/
I moved it inside the class and got the results I needed.
function validate_int($subject)
{
//Pattern is numbers
//if it matches anything but numbers, we want a fail
$pattern = '/[^0-9]/';
$matches = preg_match($pattern, $subject);
if($matches > 0)
return false;
else
return true;
}