Skip to content Skip to sidebar Skip to footer

Test If The User Has Filled All The Inputs In A Form

I have a login form in my page and I want to test if the user has filled all the inputs, this is the code I tried but it won't work :

Solution 1:

You can try it

<?php 
session_start();
require_once('bdd.inc.php');
if (isset($_POST['valider'])) {

    $auth = false;

    foreach($clients as $client)
    {
        if($_POST['login'] == $client['Pseudo'] && $_POST['mdp'] == $client['MotDePasse'])
        {
            $_SESSION['login'] = $_POST['login'];
            $_SESSION['mdp'] = $_POST['mdp'];
            $auth = true;
            break;
        }
    }

    if(!$auth)
    {
        header('location:authentification.php?auth=false');
    }
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <script type="text/javascript">
            function validation(form)
            {
                var login = document.getElementById('login');
                var mdp = document.getElementById('mdp');
                if(login.value == '' || mdp.value == '')
                    alert('You must fill in all fields!');
                else
                    form.submit();

                return false;
            }
        </script>
    </head>
    <body>

        <form method="post" action="authentification.php" id="form1" name="form1" onsubmit="validation(this);return false">
            <table>
                <tr>
                    <td>Login :</td>
                    <td><input type="text" name="login" id="login"></td>
                </tr>
                <tr>
                    <td>Mot de passe :</td>
                    <td><input type="text" name="mdp" id="mdp"></td>
                </tr>
                <tr><td colspan="2" align="center"><input type="submit" value="Valider" name="valider" id="valider"></td></tr>
                <?php
                    if(isset($_GET['auth']))
                    {
                        if($_GET['auth'] == 'false')
                        {
                            echo '<div style="color:red">Désolé, Votre pseudo ou votre mot de passe est erroné !</div>';
                        }
                    }
                ?>
            </table>
        </form>
    </body>
</html>

Solution 2:

The problem is that a browser will submit a button with type="submit" before a JavaScript scripe will finish executing. What you want to do is have your script submit your form after it validates. So change your input type to button, and do a submit from javascript itself.

EDIT: (per comment)

You already are submitting the form via JavaScript. To get your code to work, I would simply change your input button from type submit to button. so change <input type="submit" value="Valider" name="valider" id="valider"> to this:

<input type="button" value="Valider" name="valider" id="valider">

Post a Comment for "Test If The User Has Filled All The Inputs In A Form"