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

Why doesn't Gödel's incompleteness theorem apply to false statements?

Calculate Pi using Monte Carlo

How to test the sharpness of a knife?

Checking @@ROWCOUNT failing

A seasonal riddle

"Oh no!" in Latin

Reason why a kingside attack is not justified

Are hand made posters acceptable in Academia?

Reasons for having MCU pin-states default to pull-up/down out of reset

What is this high flying aircraft over Pennsylvania?

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

Has the laser at Magurele, Romania reached the tenth of the Sun power?

Highest stage count that are used one right after the other?

categorizing a variable turns it from insignificant to significant

Air travel with refrigerated insulin

Would a primitive species be able to learn English from reading books alone?

Output visual diagram of picture

How do you justify more code being written by following clean code practices?

Capacitor electron flow

Center page as a whole without centering each element individually

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Started in 1987 vs. Starting in 1987

Mac Mini (2018) 10Gb Port Compatibility

Put the phone down / Put down the phone



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













2












$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.










share|improve this question











$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















2












$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.










share|improve this question











$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













2












2








2





$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.










share|improve this question











$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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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
















  • $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










2 Answers
2






active

oldest

votes


















4












$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.






share|improve this answer











$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


















0












$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)

$password_filter1 = '/(?=.*[A-Z])/m';
$password_filter2 = '/(?=.*d)/m';

if (empty($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:



  1. Cleaner, easier to read and see what errors would be issued

  2. Easier to add, remove, or alter conditions

  3. 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)

  4. 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.






share|improve this answer









$endgroup$












    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
    );



    );













    draft saved

    draft discarded


















    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









    4












    $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.






    share|improve this answer











    $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















    4












    $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.






    share|improve this answer











    $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













    4












    4








    4





    $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.






    share|improve this answer











    $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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    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
















    • $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













    0












    $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)

    $password_filter1 = '/(?=.*[A-Z])/m';
    $password_filter2 = '/(?=.*d)/m';

    if (empty($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:



    1. Cleaner, easier to read and see what errors would be issued

    2. Easier to add, remove, or alter conditions

    3. 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)

    4. 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.






    share|improve this answer









    $endgroup$

















      0












      $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)

      $password_filter1 = '/(?=.*[A-Z])/m';
      $password_filter2 = '/(?=.*d)/m';

      if (empty($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:



      1. Cleaner, easier to read and see what errors would be issued

      2. Easier to add, remove, or alter conditions

      3. 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)

      4. 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.






      share|improve this answer









      $endgroup$















        0












        0








        0





        $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)

        $password_filter1 = '/(?=.*[A-Z])/m';
        $password_filter2 = '/(?=.*d)/m';

        if (empty($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:



        1. Cleaner, easier to read and see what errors would be issued

        2. Easier to add, remove, or alter conditions

        3. 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)

        4. 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.






        share|improve this answer









        $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)

        $password_filter1 = '/(?=.*[A-Z])/m';
        $password_filter2 = '/(?=.*d)/m';

        if (empty($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:



        1. Cleaner, easier to read and see what errors would be issued

        2. Easier to add, remove, or alter conditions

        3. 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)

        4. 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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 10 mins ago









        JamesJames

        12312




        12312



























            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar