PHP does not show me the errors in form

2

Good morning, I am creating a form in HTML and PHP, and when sending it I want you to show me an error message if any of the fields does not meet the requirement. My problem is that it only stays in the first field name if I give Send if fill nothing should show me errors in all fields, and if I have filled some field and still gives error, those fields should be filled with the entered value, until there my tests have gone well, and what is my problem?

  • Do not validate birthdate or password
  • The name is always painted on the form
  • If I write in all the fields, name, key and dateBirth are painted on the form.

My PHP code:

<head>
    <?php
        error_reporting (0);
        $partesFecha=explode("/",$_POST['fechaNacimiento']);
        $diaActual=$partesFecha[0];
        $mesActual=$partesFecha[1];
        $anyoActual=$partesFecha[2];

        if(isset($_POST['Enviar'])){
            $errores = array();
            if (!isset($_POST['nombre'])) {
                $errores[1] = '<span class="error">Introduce un nombre</span>';
            }
            if ((strlen($_POST['clave'] < 6)) && (strlen($_POST['clave']) > 12)) {
                $errores[2] = '<span class="error">La clave debe ser mayor de 6 y menor de 12 caracteres</span>';
            }
            if (!isset($_POST['genero'])) {
                $errores[3] = '<span class="error">Debes elegir un género</span>';
            }
            if ((!checkdate($mesActual, $diaActual, $anyoActual)) && (comprobarMayoriaEdad($diaActual, $mesActual, $anyoActual) < 18)) {
                $errores[4] = '<span class="error">La fecha debe ser dd/mm/yyyy y debes ser mayor de edad</span>';
            }
            if (!isset($_POST['pais'])) {
                $errores[5] = '<span class="error">Debes elegir un pais</span>';
            }
            if (!isset($_POST['acept'])) {
                $errores[6] = '<span class="error">Debes aceptar las condiciones</span>';
            } else {
                $nombre = $_POST['nombre'];
                $clave = $_POST['clave'];
                $genero = $_POST['genero'];
                $pais = $_POST['pais'];
                $acepto = $_POST['acept'];
            }
        }

        function comprobarMayoriaEdad($dia, $mes, $anyo){
            /*Fecha actual*/
            $diaAct=date("d");
            $mesAct=date("m");
            $anyoAct=date("Y");
            /*Fecha nacimiento*/
            $diaNac=$dia;
            $mesNac=$mes;
            $anyoNac=$anyo;
            /*Si el mes es el mismo pero el dia actual es inferior al que cumple años, no ha cumplido años, y restamos un año*/
            if(($mesNac==$mesAct)&&($diaNac>$diaAct)){
                $anyoAct=($anyoAct-1);
            }
            /*Si el mes actual es menor que el de nacimiento, no ha cumplido años y restamos un año*/
            if($mesNac>$mesAct){
                $anyoAct=($anyoAct-1);
            }
            /*Restamos los años para obtener la edad*/
            $edad=($anyoAct-$anyoNac);

            return $edad;
        }
    ?>
</head>

My HTML form:

<form name="Formulario" method="post" action=''>
    Nombre:
    <input type="text" name="nombre" value="<?php if(isset($_POST['nombre'])){echo $_POST['nombre'];}?>" />
    <?php if(isset($errores)){echo $errores[1];}?>
    <br/>
    <br/> Contraseña:
    <input type="password" name="clave" value="<?php if(isset($_POST['clave'])){echo $_POST['clave'];}?>" />
    <?php if(isset($errores)){echo $errores[2];}?>
    <br>
    <br/>
    <input type="radio" name="genero" value="H" />H
    <input type="radio" name="genero" value="M" />M
    <?php if(isset($errores)){echo $errores[3];}?>
    <br/>
    <br/> Fecha de nacimiento:
    <input type="text" name="fechaNacimiento" value="<?php if(isset($_POST['fechaNacimiento'])){echo $_POST['fechaNacimiento'];}?>" />
    <?php if(isset($errores)){echo $errores[4];}?>
    <br/>
    <br/>
    <select name="pais[]" multiple="multiple">
        <option value="España">España</option>
        <option value="Francia">Francia</option>
        <option value="Italia">Italia</option>
    </select>
    <?php if(isset($errores)){echo $errores[5];}?>
    <br/>
    <br/> Acepto las condiciones:
    <input type="checkbox" name="acept" value="OK" />
    <?php if(isset($errores)){echo $errores[6];}?>
    <br>
    <br/> Comentarios:
    <textarea name="comentarios" rows="10" cols="30" value=""></textarea>
    <br>
    <br/> Foto:
    <input type="file" name="foto" />
    <br/>
    <br/>
    <br/>
    <input type="submit" name="Enviar" value="Enviar" />
</form>
    
asked by NeoChiri 20.10.2016 в 18:35
source

4 answers

2

Check the conditions. Some contain errors and will never be entered. You also have to keep in mind that some types of fields are never sent, while others are only sent when you have "interacted" with them (for example radios and checkboxes).

We are going to see the fields and validations one by one:

The name is a text type ( input type='text' ) so it will always be sent with the form (even if it is empty), so it will always be considered valid, even if it is send empty You should not only check that it is, but also that it should be of a size (you would really have left over with this last one):

if ($_POST['nombre'] != "") {

Then the key has the bad check:

if ((strlen($_POST['clave'] < 6)) && (strlen($_POST['clave']) > 12)) {

It is never going to happen that the length of the key is both less than 6 and greater than 12, you should use || instead of && because what you want to check is that the length of the key is not less than 6 or greater than 12:

if ((strlen($_POST['clave'] < 6)) || (strlen($_POST['clave']) > 12)) {

The date of birth fails because in the function comprobarMayoriaEdad the case in which the date is empty is not checked. What makes that if no date has been passed, then the calculated age will be equal to the current year (always of legal age).

Also, it has the same problem as the key, the if should be with a || or you will find the problem that either both are met or no error will be displayed. Then it should be something like this:

if ((!checkdate($mesActual, $diaActual, $anyoActual)) || (comprobarMayoriaEdad($diaActual, $mesActual, $anyoActual) < 18)) {

And in the comprobarMayoriaEdad function you could add a first line that returns 0 if the year ( $anyo ) is not specified:

function comprobarMayoriaEdad($dia, $mes, $anyo){
    if (!$anyo) return 0;
    ....

Now, about the fields that remain painted. That happens because you're writing them in PHP:

<input type="text" name="nombre" value="<?php if(isset($_POST['nombre'])){echo $_POST['nombre'];}?>" />
...
<input type="password" name="clave" value="<?php if(isset($_POST['clave'])){echo $_POST['clave'];}?>" />
...
<input type="text" name="fechaNacimiento" value="<?php if(isset($_POST['fechaNacimiento'])){echo $_POST['fechaNacimiento'];}?>" />
...

What you could do is add a variable when all the checks have been made and are correct and only show the values if something went wrong.

    
answered by 20.10.2016 / 19:43
source
1

It seems to me that validating the fields in your form is easier if you do it with Jquery. I usually use this plugin   link

Another possible solution is to add the required property to the DOM elements

<input type="radio" name="genero" value="H" required="true" />

And for the password it would be something like that

<input type="radio" name="genero" value="H" required="true" maxlength="12"/>

maxlenght, it will not show you a message, it is the maximum number of characters that the user can enter

    
answered by 20.10.2016 в 19:23
0
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <?php
    error_reporting (0);
    $partesFecha=explode("/",$_POST['fechaNacimiento']);
    $diaActual=$partesFecha[0];
    $mesActual=$partesFecha[1];
    $anyoActual=$partesFecha[2];

    if(isset($_POST['Enviar'])){
        $errores = array();
        if ( $_POST['nombre'] == '' ) {
            $errores[1] = '<span class="error">Introduce un nombre</span>';
        }
        if ( strlen($_POST['clave']) < 6 or strlen($_POST['clave']) > 12 ) {
            $errores[2] = '<span class="error">La clave debe ser mayor de 6 y menor de 12 caracteres</span>';
        }
        if (!isset($_POST['genero'])) {
            $errores[3] = '<span class="error">Debes elegir un género</span>';
        }
        if (!checkdate($mesActual, $diaActual, $anyoActual) && comprobarMayoriaEdad($diaActual, $mesActual, $anyoActual) < 18) {
            $errores[4] = '<span class="error">La fecha debe ser dd/mm/yyyy y debes ser mayor de edad</span>';
        }
        if (!isset($_POST['pais'])) {
            $errores[5] = '<span class="error">Debes elegir un pais</span>';
        }
        if (!isset($_POST['acept'])) {
            $errores[6] = '<span class="error">Debes aceptar las condiciones</span>';
        } else {
            $nombre = $_POST['nombre'];
            $clave = $_POST['clave'];
            $genero = $_POST['genero'];
            $pais = $_POST['pais'];
            $acepto = $_POST['acept'];
        }
    }

    function comprobarMayoriaEdad($dia, $mes, $anyo){
        /*Fecha actual*/
        $diaAct=date("d");
        $mesAct=date("m");
        $anyoAct=date("Y");
        /*Fecha nacimiento*/
        $diaNac=$dia;
        $mesNac=$mes;
        $anyoNac=$anyo;
        /*Si el mes es el mismo pero el dia actual es inferior al que cumple años, no ha cumplido años, y restamos un año*/
        if(($mesNac==$mesAct)&&($diaNac>$diaAct)){
            $anyoAct=($anyoAct-1);
        }
        /*Si el mes actual es menor que el de nacimiento, no ha cumplido años y restamos un año*/
        if($mesNac>$mesAct){
            $anyoAct=($anyoAct-1);
        }
        /*Restamos los años para obtener la edad*/
        $edad=($anyoAct-$anyoNac);

        return $edad;
    }
    ?>
</head>
<body>
    <form name="Formulario" method="post" action='' autocomplete="off" >
        Nombre:
        <input type="text" name="nombre" value="<?php if(isset($_POST['nombre'])){echo $_POST['nombre'];}?>" />
        <?php if(isset($errores)){echo $errores[1];}?>
        <br/>
        <br/> Contraseña:
        <input type="password" name="clave" value="<?php if(isset($_POST['clave'])){echo $_POST['clave'];}?>" />
        <?php if(isset($errores)){echo $errores[2];}?>
        <br>
        <br/>
        <input type="radio" name="genero" value="H" />H
        <input type="radio" name="genero" value="M" />M
        <?php if(isset($errores)){echo $errores[3];}?>
        <br/>
        <br/> Fecha de nacimiento:
        <input type="text" name="fechaNacimiento" value="<?php if(isset($_POST['fechaNacimiento'])){echo $_POST['fechaNacimiento'];}?>" />
        <?php if(isset($errores)){echo $errores[4];}?>
        <br/>
        <br/>
        <select name="pais[]" multiple="multiple">
            <option value="España">España</option>
            <option value="Francia">Francia</option>
            <option value="Italia">Italia</option>
        </select>
        <?php if(isset($errores)){echo $errores[5];}?>
        <br/>
        <br/> Acepto las condiciones:
        <input type="checkbox" name="acept" value="OK" />
        <?php if(isset($errores)){echo $errores[6]; var_dump($errores); }?>
        <br>
        <br/> Comentarios:
        <textarea name="comentarios" rows="10" cols="30" value=""></textarea>
        <br>
        <br/> Foto:
        <input type="file" name="foto" />
        <br/>
        <br/>
        <br/>
        <input type="submit" name="Enviar" value="Enviar" />
    </form>
</body>
</html>

Fix you some things first there is more parenthesis of the appropriate in the sentences of the IF second you put if(!isset($_POST['nombre'])) this feels false because if you send the form already exists what you had to validate is that it is empty or not

Recommendation: What you want to leave error for empty or not use other than the required html5 tag for the date use the date type and since you can not be several paris, take away from the countries the fact that it is an array.

    
answered by 20.10.2016 в 19:26
0

1.1) In code you must change the && for || since you are saying that if the key is LESS THAN 6 AND GREATER THAN 12 you must meet those 2 conditions ...

1.2) You must also change the operation && by || because you are also validating the format, if it complies with the format dd / mm / yyyy And it is not minor then it would enter to show the error, however if it is of age BUT the format is wrong not valid would not show the error. In this option I would separate the validations would be the order

if ((!checkdate($mesActual, $diaActual, $anyoActual)){
     echo "error en fecha formato"
}else if (comprobarMayoriaEdad($diaActual, $mesActual, $anyoActual) < 18){
     echo "menor de edad";
}

And as a second error, they are "painted" because you do not update them, what I would do would be to set variables from validation to HTML directly

if($clave < 6 || $clave > 12){
    $error_clave = true;
}

HTML

 <input type="password" name="clave" value="<?php if(isset($_POST['clave'])){echo $_POST['clave'];}?>" />
 <?php if($error_clave){
      echo '<span class="error">Error en la clave</span>'
   }
 ?>
    
answered by 20.10.2016 в 20:33