This question already has an answer here:
Reference - Password Validation
(1 answer)
Closed 5 years ago.
I am trying to establish password parameters to be 8-20 characters long, at least one upper case character, number, and symbol. I have written the code as such
(preg_match ('/^(\W+)(\d+)([A-Z]+)([a-z]+){8,20}$/', $_POST['pass1']) )
My interpretation of my code is as follows:
W+ one or more symbols (non alpha numeric)
d+ one or more numbers
[A-Z]+ one or more uppercase characters
[a-z]+ one or more lower case characters
{8,20} string length min 8 max 20
When I enter the password as Anyhelp4me! I get an invalid password message. What are your suggestions.
Don't do it all with one regex. It will be far more maintainable, understandable, and easier to change in the future if you make multiple calls to preg_match with multiple regexes.
$password_is_ok =
preg_match( '/\W/', $pass ) &&
preg_match( '/\d/', $pass ) &&
preg_match( '/[a-z]/', $pass ) &&
preg_match( '/[A-Z]/', $pass ) &&
strlen( $pass ) >= 8 &&
strlen( $pass ) <= 20;
That is far more readable and understandable by the next person who has to read your code (who might be you) than any single-regex monstrosity you can concoct.
Okay...I tried the previous recommendation and it only imposed the "8,10" restriction. I found this on stackoverflow "Create preg_match for password validation allowing (!##$%)" and modified the code presented in that response as follows:
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\W)[0-9A-Za-z!##$%]{8,20}$/
I have tested it several times and it does work. You have to have at least one digit, one uppercase, one lower case and a specified symbol (!##$%) and between 8 and 20 characters.
Related
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular expression to limit number of characters to 10
I retrieve a POST to a standard form and I need to test two things:
The value must be 40 characters
The value must contain only letters and numbers
I think it is possible to do this with preg_match, but I do not know how.
In the global $_POST you have all your posted data on the http request.
then:
$myvar = $_POST['your_posted_variable_here'];
$result = preg_match('/^([\w\d]){40}$/i', $myvar);
$result will be true if your posted data only contains letters and digits and is 40 characters long, otherwise will be false.
For exactly 40 characters:
^[a-zA-Z0-9]{40}$
For at least 40 characters:
^[a-zA-Z0-9]{40,}$
Information on preg_match
http://php.net/manual/en/function.preg-match.php
if (preg_match("#^[a-z0-9]{40}$#mis", $_POST['username'])) {
print 'matched';
}
You can also check the length of the string using strlen() first, then if it satisfies the desired length, go forth with the checking of alpha numerics.
But General has the right idea...
Here's another way:
preg_match("/^[0-9a-zA-Z_]{40,}$/", $_POST["something"])
This is alpha numeric, and checks for at least 40 characters, but will accept more. The missing value after the comma means that it can be of any value equal or bigger than 40.
PHP provides a function for checking alphanumeric characters ctype_alnum and strlen to check the length of a string so using both functions you can validate it
$yourInput=$_POST['yourInput'];
if(ctype_alnum($yourInput) && strlen($strlen)==40)
{
//...
}
This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 4 years ago.
I've been searching for hours to find a regex that does this for me, all the ones I've found either require dashes or limit something else that I don't need.
Like this one:
^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Basically I want to allow these types of input for phone number, these are all valid:
+000 111111111
+00011111111111
0022 111111111111
0022111111111
+333-4444-5555-6666
000-7878787-0000-4587
Note that the number of digits is not limited, I only want the validation to filter out empty inputs and the alphabet. Also filter out all other characters except a maximum of 4 dashes, max. 4 spaces and an optional single plus sign.
Is this possible through preg_match or not?
Any help is appreciated, thanks!
Sure its possible. But to my opinion dangerous to use stuff that is not understood. I would do something like this
^(?!(?:\d*-){5,})(?!(?:\d* ){5,})\+?[\d- ]+$
See it here on Regexr
The last part \+?[\d- ]+ allows an optional + followed by at least one digit, dash or space
The negative lookaheads ensure that there are not more than 4 dash or spaces.
Limitations:
- The dash or space can be in one row
- it accepts also - as valid
Try it yourself on the Regexr link, you can just add examples what you want.
Strip wanted characters out (" ", "-"), count the amount then chuck an if statement if count <= 4 (for the "+" character it would be == 1). So in total it would be
if (countSpace <= 4 && countDash <= 4 && countPlus == 1) {
...
}
As for being empty, just use the standard form validation for checking if the input has been filled or not.
My users have a cookie with a string called code in it, the code is just random numbers or letters between 6 and 15 characters long. How after I receive the code, how can I check to ensure that the code is between 6 and 15 characters long and only contains numbers and letters?
Is using regular expressions the best way?
There are two easy ways you can do this. One is using regular expressions:
$length = strlen($cookie);
if (6 <= $length && $length <= 15 && preg_match('/^[a-zA-Z0-9]*$/', $cookie)) {
//...
}
The other is using the built-in ctype_alnum function which does exactly that (making sure a string is alpha-numeric):
$length = strlen($cookie);
if (6 <= $length && $length <= 15 && ctype_alnum($cookie)) {
//...
}
I would try something like : ^([a-zA-Z]|\d){6,15}$
“between the beginning and the end of the string, there are between 6 and 15 characters, each of them a letter or a digit”.
And, oh, the function you need is preg_match()
php's regex is pretty quick, and this is a case of a simple selector:
"/^[a-zA-Z0-9]{6,15}$/"
But #amosrivera was right about strlen being faster. If the cookie data is being plugged in the page (echo $_COOKIE['key'];) then the XML entities wont matter as the user can only harm their own page. If the cookie is being stored in a database and being displayed for all users, it would be a different matter altogether.
This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 9 years ago.
How to validate phone number using php
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T