0

I'm creating registration form, and want to before clicking on submit button to change <input>'s CSS properties when the passwords don't match (change background color).

if ($_POST["pass"] != $_POST["pass_again"]){
    $message = "Passwords don't match";
    echo ('
        <script type="text/javascript"> 
            document.getElementById("pass_again").background-color = "red";
        </script>
    ');
}
Revivalo
  • 3
  • 4
  • 4
    You'd want to do this at the client level first and then at the server level. – Scott Marcus May 20 '19 at 15:46
  • You're mixing up client-side execution with the server-side script here. You can validate if the passwords are identical in javascript on the client side. Later, re-check this on the server-side. Edit: Just a bit too slow - Scott was faster ;) – Kryptur May 20 '19 at 15:47
  • But how I can re-check this on the server-side? – Revivalo May 20 '19 at 15:49
  • Check this problem in code $message = 'Passwords dont match'; – Kamlesh Jain May 20 '19 at 15:52
  • [This might be helpful](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) - you need to understand how server-side code (e.g. PHP) actually works - or rather why you can't update the client, dynamically, with PHP. – CD001 May 20 '19 at 15:53
  • You already have the code in your example. On serverside, you have to check if `$_POST["pass"] == $_POST["pass_again"]` – Kryptur May 20 '19 at 15:53
  • Only single quat not allow use abow code – Kamlesh Jain May 20 '19 at 15:54
  • why not use [input:valid](https://www.w3schools.com/cssref/sel_valid.asp) css? – Rachel Gallen May 20 '19 at 15:57
  • @Rachel Gallen it doesn't check, if the passwords are the same. – Revivalo May 20 '19 at 15:58
  • @Revivalo ah of course.. gotcha. Worth integrating on client side to check the fields are filled though.. – Rachel Gallen May 20 '19 at 15:59

1 Answers1

0

If you want to validate on the server-side after they submit the form and want to change the look, you could set the class of the input elements as you write them out instead of trying to do it with Javascript afterwards.

Something like this..

<?php
$class = ($_POST['pass'] == $_POST['pass_again']) ? 'valid' : 'invalid';
?>
<style>
    .valid {
        bakground-color: green;
    }
    .invalid {
        background-color: red;
    }
</style>
<form method="post">
    <input class="<?php echo $class; ?>" type="password" name="pass" id="pass">
    <input class="<?php echo $class; ?>" type="password" name="pass_again" id="pass_again">
    <button type="submit">Login</button>
</form>

Please note I didn't validate that this code has no bugs but you should get the idea.

MER
  • 328
  • 2
  • 9