Validation for registration passwordSpring password validator libraryRegistration form with validation and error messagesA Simple, One-Page PHP Admin Login (with prepared SQL statements)Registration, Validation & Storage functionsRegistration form validation in jQueryPassword Validation in PythonUser ID & password constraints checkerInputs equality check using jQuery without pluginsPHP validation class for username, email, and passwordusing $_POST array to prepare PDO statement with variables
Friend wants my recommendation but I don't want to give it to him
How to test the sharpness of a knife?
What is the purpose of using a decision tree?
Why is indicated airspeed rather than ground speed used during the takeoff roll?
Toggle window scroll bar
New Order #2: Turn My Way
If the Dominion rule using their Jem'Hadar troops, why is their life expectancy so low?
Do native speakers use "ultima" and "proxima" frequently in spoken English?
Center page as a whole without centering each element individually
Why didn’t Eve recognize the little cockroach as a living organism?
Has the laser at Magurele, Romania reached the tenth of the Sun power?
Sort with assumptions
1 John in Luther’s Bibel
Why is "la Gestapo" feminine?
Pre-Employment Background Check With Consent For Future Checks
When is the exact date for EOL of Ubuntu 14.04 LTS?
Weird lines in Microsoft Word
What do the positive and negative (+/-) transmit and receive pins mean on Ethernet cables?
How do you say "Trust your struggle." in French?
Is this saw blade faulty?
Travelling in US for more than 90 days
How to detect sounds in IPA spelling
What should be the ideal length of sentences in a blog post for ease of reading?
Can you take a "free object interaction" while incapacitated?
Validation for registration password
Spring password validator libraryRegistration form with validation and error messagesA Simple, One-Page PHP Admin Login (with prepared SQL statements)Registration, Validation & Storage functionsRegistration form validation in jQueryPassword Validation in PythonUser ID & password constraints checkerInputs equality check using jQuery without pluginsPHP validation class for username, email, and passwordusing $_POST array to prepare PDO statement with variables
$begingroup$
Could someone tell me if this is a bad idea for coding my validation for a password and it is bad? This is for registration for my site. Could you please tell me why and how you would go about it (I am a beginner and at PHP)?
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
if (!empty($password & $confirm_password))
if ($password === $confirm_password)
if (preg_match($password_filter1, $password))
if (preg_match($password_filter2, $password))
if (preg_match($password_filter3, $password))
//If everything is true do this
else
$password_error = "Your password must contain at least 1 number";
else
$password_error = "You're password must have at least 1 capital letter";
else
$password_error = "You're password must be at least 6 characters long";
else
$password_error = "The passwords do not match";
else
$password_error = "You must enter a password";
The only reason why I am not doing all the filters in 1 preg_match
is because I would like specific errors.
php validation
$endgroup$
add a comment |
$begingroup$
Could someone tell me if this is a bad idea for coding my validation for a password and it is bad? This is for registration for my site. Could you please tell me why and how you would go about it (I am a beginner and at PHP)?
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
if (!empty($password & $confirm_password))
if ($password === $confirm_password)
if (preg_match($password_filter1, $password))
if (preg_match($password_filter2, $password))
if (preg_match($password_filter3, $password))
//If everything is true do this
else
$password_error = "Your password must contain at least 1 number";
else
$password_error = "You're password must have at least 1 capital letter";
else
$password_error = "You're password must be at least 6 characters long";
else
$password_error = "The passwords do not match";
else
$password_error = "You must enter a password";
The only reason why I am not doing all the filters in 1 preg_match
is because I would like specific errors.
php validation
$endgroup$
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54
add a comment |
$begingroup$
Could someone tell me if this is a bad idea for coding my validation for a password and it is bad? This is for registration for my site. Could you please tell me why and how you would go about it (I am a beginner and at PHP)?
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
if (!empty($password & $confirm_password))
if ($password === $confirm_password)
if (preg_match($password_filter1, $password))
if (preg_match($password_filter2, $password))
if (preg_match($password_filter3, $password))
//If everything is true do this
else
$password_error = "Your password must contain at least 1 number";
else
$password_error = "You're password must have at least 1 capital letter";
else
$password_error = "You're password must be at least 6 characters long";
else
$password_error = "The passwords do not match";
else
$password_error = "You must enter a password";
The only reason why I am not doing all the filters in 1 preg_match
is because I would like specific errors.
php validation
$endgroup$
Could someone tell me if this is a bad idea for coding my validation for a password and it is bad? This is for registration for my site. Could you please tell me why and how you would go about it (I am a beginner and at PHP)?
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
if (!empty($password & $confirm_password))
if ($password === $confirm_password)
if (preg_match($password_filter1, $password))
if (preg_match($password_filter2, $password))
if (preg_match($password_filter3, $password))
//If everything is true do this
else
$password_error = "Your password must contain at least 1 number";
else
$password_error = "You're password must have at least 1 capital letter";
else
$password_error = "You're password must be at least 6 characters long";
else
$password_error = "The passwords do not match";
else
$password_error = "You must enter a password";
The only reason why I am not doing all the filters in 1 preg_match
is because I would like specific errors.
php validation
php validation
edited Jan 3 '17 at 2:03
Phrancis
14.8k649142
14.8k649142
asked Jan 3 '17 at 0:58
AshAsh
204
204
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54
add a comment |
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.
Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
There is also no need for m
multiline flag for a password, since passwords shouldn't accept any newline characters.
Compare to:
$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*d)/';
You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.
function has_a_capital_letter($str)
return preg_match('/(?=.*[A-Z])/', $str);
//...
if (!has_a_capital_letter($password))
$password_error = "Your password must have at least 1 capital letter";
There is no real value in nesting multiple if/else
statements inside each other like this, when a simple sequence of if/elseif/else
will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.
It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.
This is much simpler and cleaner:
if (empty($password & $confirm_password))
$password_error = "You must enter a password";
elseif ($password !== $confirm_password)
$password_error = "The passwords do not match";
elseif (!preg_match($has_at_least_6_chars, $password))
$password_error = "Your password must be at least 6 characters long";
elseif (!preg_match($has_a_capital_letter, $password))
$password_error = "Your password must have at least 1 capital letter";
elseif (!preg_match($has_a_digit, $password))
$password_error = "Your password must contain at least 1 number";
else
//If everything is true do this
By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/m'
in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:
$password = "Hell0!";
$confirm_password = "Hell0!";
Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the !
and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen()
PHP function.
elseif (strlen($password) < 6)
$password_error = "Your password must be at least 6 characters long";
That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.
$endgroup$
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
add a comment |
$begingroup$
If you split things out into (ideally) classes or at least functions, you can have cleaner code as well as reuse things on different pages or in different functions or classes. For example see the refactor of your if/else checking for a valid password:
While this code should work, it's not tested, so please don't use in production without usual considerations and testing.
function getPasswordError($password, $confirm_password)
You can check it such as:
$password_error = getPasswordError($password, $confirm_password);
if ($password_error !== false)
echo $password_error; // or do whatever with the data
The thing about that function is:
- Cleaner, easier to read and see what errors would be issued
- Easier to add, remove, or alter conditions
- Reusable - if in a separate file somewhere then the function can be used in other places (eg the login form and registration as both need the same validation)
- Return early (as soon as something fails etc go back)
Note: That I've put your filters inside the function. You could pass them in, and will in some functions to have control, but likely you wouldn't want to ever have different criteria for those filters. That would (likely) be a different function for a different purpose (even if the same conditions).
Also the function could be better named, but given your other code there's not much to do. E.g. I would have a function that determined if valid or not and just returned bools, then if something failed then issue a specific message.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f151511%2fvalidation-for-registration-password%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.
Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
There is also no need for m
multiline flag for a password, since passwords shouldn't accept any newline characters.
Compare to:
$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*d)/';
You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.
function has_a_capital_letter($str)
return preg_match('/(?=.*[A-Z])/', $str);
//...
if (!has_a_capital_letter($password))
$password_error = "Your password must have at least 1 capital letter";
There is no real value in nesting multiple if/else
statements inside each other like this, when a simple sequence of if/elseif/else
will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.
It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.
This is much simpler and cleaner:
if (empty($password & $confirm_password))
$password_error = "You must enter a password";
elseif ($password !== $confirm_password)
$password_error = "The passwords do not match";
elseif (!preg_match($has_at_least_6_chars, $password))
$password_error = "Your password must be at least 6 characters long";
elseif (!preg_match($has_a_capital_letter, $password))
$password_error = "Your password must have at least 1 capital letter";
elseif (!preg_match($has_a_digit, $password))
$password_error = "Your password must contain at least 1 number";
else
//If everything is true do this
By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/m'
in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:
$password = "Hell0!";
$confirm_password = "Hell0!";
Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the !
and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen()
PHP function.
elseif (strlen($password) < 6)
$password_error = "Your password must be at least 6 characters long";
That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.
$endgroup$
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
add a comment |
$begingroup$
First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.
Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
There is also no need for m
multiline flag for a password, since passwords shouldn't accept any newline characters.
Compare to:
$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*d)/';
You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.
function has_a_capital_letter($str)
return preg_match('/(?=.*[A-Z])/', $str);
//...
if (!has_a_capital_letter($password))
$password_error = "Your password must have at least 1 capital letter";
There is no real value in nesting multiple if/else
statements inside each other like this, when a simple sequence of if/elseif/else
will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.
It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.
This is much simpler and cleaner:
if (empty($password & $confirm_password))
$password_error = "You must enter a password";
elseif ($password !== $confirm_password)
$password_error = "The passwords do not match";
elseif (!preg_match($has_at_least_6_chars, $password))
$password_error = "Your password must be at least 6 characters long";
elseif (!preg_match($has_a_capital_letter, $password))
$password_error = "Your password must have at least 1 capital letter";
elseif (!preg_match($has_a_digit, $password))
$password_error = "Your password must contain at least 1 number";
else
//If everything is true do this
By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/m'
in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:
$password = "Hell0!";
$confirm_password = "Hell0!";
Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the !
and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen()
PHP function.
elseif (strlen($password) < 6)
$password_error = "Your password must be at least 6 characters long";
That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.
$endgroup$
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
add a comment |
$begingroup$
First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.
Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
There is also no need for m
multiline flag for a password, since passwords shouldn't accept any newline characters.
Compare to:
$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*d)/';
You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.
function has_a_capital_letter($str)
return preg_match('/(?=.*[A-Z])/', $str);
//...
if (!has_a_capital_letter($password))
$password_error = "Your password must have at least 1 capital letter";
There is no real value in nesting multiple if/else
statements inside each other like this, when a simple sequence of if/elseif/else
will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.
It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.
This is much simpler and cleaner:
if (empty($password & $confirm_password))
$password_error = "You must enter a password";
elseif ($password !== $confirm_password)
$password_error = "The passwords do not match";
elseif (!preg_match($has_at_least_6_chars, $password))
$password_error = "Your password must be at least 6 characters long";
elseif (!preg_match($has_a_capital_letter, $password))
$password_error = "Your password must have at least 1 capital letter";
elseif (!preg_match($has_a_digit, $password))
$password_error = "Your password must contain at least 1 number";
else
//If everything is true do this
By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/m'
in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:
$password = "Hell0!";
$confirm_password = "Hell0!";
Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the !
and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen()
PHP function.
elseif (strlen($password) < 6)
$password_error = "Your password must be at least 6 characters long";
That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.
$endgroup$
First a stylistic note: you should always use at least 2 spaces of indentation for code; 1 space makes it very difficult to read nested statements in particular. PHP most often uses 4 spaces for indent.
Your regular expressions wouldn't need comments to explain them if you gave them meaningful names.
$password_filter1 = '/(?=.*[a-zA-Z0-9]6)/m'; //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m'; //Capital letter
$password_filter3 = '/(?=.*d)/m'; //A digit
There is also no need for m
multiline flag for a password, since passwords shouldn't accept any newline characters.
Compare to:
$has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/';
$has_a_capital_letter = '/(?=.*[A-Z])/';
$has_a_digit = '/(?=.*d)/';
You may also consider making them into small functions so they are reusable elsewhere in the code, and if you needed to change them later you would just change them in one place.
function has_a_capital_letter($str)
return preg_match('/(?=.*[A-Z])/', $str);
//...
if (!has_a_capital_letter($password))
$password_error = "Your password must have at least 1 capital letter";
There is no real value in nesting multiple if/else
statements inside each other like this, when a simple sequence of if/elseif/else
will work just as good. Nesting like that with even simple conditions makes the code quite hard to read, in fact. Nesting like this with more complex operations could lead to serious performance bottlenecks as it cannot break early as easily.
It's also simpler to test for the existence of conditions instead of the lack of them, and just break out of the conditionals as soon as a condition is met.
This is much simpler and cleaner:
if (empty($password & $confirm_password))
$password_error = "You must enter a password";
elseif ($password !== $confirm_password)
$password_error = "The passwords do not match";
elseif (!preg_match($has_at_least_6_chars, $password))
$password_error = "Your password must be at least 6 characters long";
elseif (!preg_match($has_a_capital_letter, $password))
$password_error = "Your password must have at least 1 capital letter";
elseif (!preg_match($has_a_digit, $password))
$password_error = "Your password must contain at least 1 number";
else
//If everything is true do this
By the way, I think there is a problem with $has_at_least_6_chars = '/(?=.*[a-zA-Z0-9]6)/m'
in that it doesn't truly check for 6 characters, it checks for 6 letters and/or numbers. According to the way your error messages are written, this should be a perfectly valid entry meeting all conditions:
$password = "Hell0!";
$confirm_password = "Hell0!";
Yet your code returns "Your password must be at least 6 characters long" (which of course it is, except that your regular expression removes the !
and all other non-alphanumeric characters). It would be much simpler (and more accurate) to use the built-in strlen()
PHP function.
elseif (strlen($password) < 6)
$password_error = "Your password must be at least 6 characters long";
That is, unless you have requirements that forbid non-alphanumeric characters, which I think would be a terrible idea, since many people use them to make for stronger passwords that are harder to break through brute force.
edited Jan 4 '17 at 9:01
answered Jan 3 '17 at 2:58
PhrancisPhrancis
14.8k649142
14.8k649142
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
add a comment |
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
$begingroup$
This is so helpful thank you so much I shall be book marking this for future use! Thanks again!
$endgroup$
– Ash
Jan 4 '17 at 7:09
add a comment |
$begingroup$
If you split things out into (ideally) classes or at least functions, you can have cleaner code as well as reuse things on different pages or in different functions or classes. For example see the refactor of your if/else checking for a valid password:
While this code should work, it's not tested, so please don't use in production without usual considerations and testing.
function getPasswordError($password, $confirm_password)
You can check it such as:
$password_error = getPasswordError($password, $confirm_password);
if ($password_error !== false)
echo $password_error; // or do whatever with the data
The thing about that function is:
- Cleaner, easier to read and see what errors would be issued
- Easier to add, remove, or alter conditions
- Reusable - if in a separate file somewhere then the function can be used in other places (eg the login form and registration as both need the same validation)
- Return early (as soon as something fails etc go back)
Note: That I've put your filters inside the function. You could pass them in, and will in some functions to have control, but likely you wouldn't want to ever have different criteria for those filters. That would (likely) be a different function for a different purpose (even if the same conditions).
Also the function could be better named, but given your other code there's not much to do. E.g. I would have a function that determined if valid or not and just returned bools, then if something failed then issue a specific message.
$endgroup$
add a comment |
$begingroup$
If you split things out into (ideally) classes or at least functions, you can have cleaner code as well as reuse things on different pages or in different functions or classes. For example see the refactor of your if/else checking for a valid password:
While this code should work, it's not tested, so please don't use in production without usual considerations and testing.
function getPasswordError($password, $confirm_password)
You can check it such as:
$password_error = getPasswordError($password, $confirm_password);
if ($password_error !== false)
echo $password_error; // or do whatever with the data
The thing about that function is:
- Cleaner, easier to read and see what errors would be issued
- Easier to add, remove, or alter conditions
- Reusable - if in a separate file somewhere then the function can be used in other places (eg the login form and registration as both need the same validation)
- Return early (as soon as something fails etc go back)
Note: That I've put your filters inside the function. You could pass them in, and will in some functions to have control, but likely you wouldn't want to ever have different criteria for those filters. That would (likely) be a different function for a different purpose (even if the same conditions).
Also the function could be better named, but given your other code there's not much to do. E.g. I would have a function that determined if valid or not and just returned bools, then if something failed then issue a specific message.
$endgroup$
add a comment |
$begingroup$
If you split things out into (ideally) classes or at least functions, you can have cleaner code as well as reuse things on different pages or in different functions or classes. For example see the refactor of your if/else checking for a valid password:
While this code should work, it's not tested, so please don't use in production without usual considerations and testing.
function getPasswordError($password, $confirm_password)
You can check it such as:
$password_error = getPasswordError($password, $confirm_password);
if ($password_error !== false)
echo $password_error; // or do whatever with the data
The thing about that function is:
- Cleaner, easier to read and see what errors would be issued
- Easier to add, remove, or alter conditions
- Reusable - if in a separate file somewhere then the function can be used in other places (eg the login form and registration as both need the same validation)
- Return early (as soon as something fails etc go back)
Note: That I've put your filters inside the function. You could pass them in, and will in some functions to have control, but likely you wouldn't want to ever have different criteria for those filters. That would (likely) be a different function for a different purpose (even if the same conditions).
Also the function could be better named, but given your other code there's not much to do. E.g. I would have a function that determined if valid or not and just returned bools, then if something failed then issue a specific message.
$endgroup$
If you split things out into (ideally) classes or at least functions, you can have cleaner code as well as reuse things on different pages or in different functions or classes. For example see the refactor of your if/else checking for a valid password:
While this code should work, it's not tested, so please don't use in production without usual considerations and testing.
function getPasswordError($password, $confirm_password)
You can check it such as:
$password_error = getPasswordError($password, $confirm_password);
if ($password_error !== false)
echo $password_error; // or do whatever with the data
The thing about that function is:
- Cleaner, easier to read and see what errors would be issued
- Easier to add, remove, or alter conditions
- Reusable - if in a separate file somewhere then the function can be used in other places (eg the login form and registration as both need the same validation)
- Return early (as soon as something fails etc go back)
Note: That I've put your filters inside the function. You could pass them in, and will in some functions to have control, but likely you wouldn't want to ever have different criteria for those filters. That would (likely) be a different function for a different purpose (even if the same conditions).
Also the function could be better named, but given your other code there's not much to do. E.g. I would have a function that determined if valid or not and just returned bools, then if something failed then issue a specific message.
answered 8 mins ago
JamesJames
12312
12312
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f151511%2fvalidation-for-registration-password%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
You shouldn't leave out important parts of the code, such as the code that is executed if all validations pass, and your $password_filter 1-3.
$endgroup$
– Phrancis
Jan 3 '17 at 1:10
$begingroup$
Just as well, you should include whether this is registration password validation, or login password validation.
$endgroup$
– Der Kommissar
Jan 3 '17 at 1:44
$begingroup$
@EBrown yes sorry this is registration password
$endgroup$
– Ash
Jan 3 '17 at 1:54
$begingroup$
@Phrancis this is just to check if the password is okay to send to the database
$endgroup$
– Ash
Jan 3 '17 at 1:54