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













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)



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









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



    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









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



      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









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



        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









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



        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











        share


        share










        answered 8 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

            कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

            Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

            चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि