简体   繁体   中英

Validate form before submitted (Check all fields are entered)

I'm trying to check that the fields in the form below have been filled before it can be inserted into a database eg display a pop up with the fields that have not been filled in. It is just a simple Registration form.

<form name="form1" method="post" action="signup_ac.php">
<strong>Sign up</strong>
Username:<input name="username" type="text" id="username" size="30">
Password:<input name="password" type="password" id="password" size="15">
Name:<input name="name" type="text" id="name" size="30">
<select name="Month">
<option selected>Month</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option
  </select> 
<select name=Year>
<option selected>Year</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
 </select>
<input type="submit" name="Submit" value="Submit"> &nbsp;
<input type="reset" name="Reset" value="Reset">
</form>

How do I do this using JavaScript or jQuery.

First of all, download the jQuery validate plugin and add it to your page. Then give each input you want to make a required field a class of required . Then in jQuery:

$(function() {
    $("form").validate();
});

The validate plugin is very feature rich, so you can have different types of message displayed, different validation checks etc should you require. There's more information on that in the documentation .

Finally, as with all javascript front-end validation, make sure you validate user input on the server side too, just in case a user has javascript turned off in their browser.

Another way:

if($_SERVER['REQUEST_METHOD']=='POST'){

require('inc/mysqli_connect.php');
$errors=array();

/*Verifica el nombre*/
if(empty($_POST['first_name'])){
    $errors[]='Verifique el campo de Nombre del participante';
}else{
    $fina=mysqli_real_escape_string($dbc, trim($_POST['first_name']));
}

/*Verifica el apellido paterno*/
if(empty($_POST['ape_pat'])){
    $errors[]='Verifique el campo de Apellido Paterno del participante';
}else{
    $appa=mysqli_real_escape_string($dbc, trim($_POST['ape_pat']));
}

/*Verifica el apellido materno*/
if(empty($_POST['ape_mat'])){
    $errors[]='Verifique el campo de Apellido Materno del participante';
}else{
    $apma=mysqli_real_escape_string($dbc, trim($_POST['ape_mat']));
}

/*Verifica el genero*/
if(empty($_POST['gender'])){
    $errors[]='Seleccione el Género del participante';
}else{
    $gend=mysqli_real_escape_string($dbc, trim($_POST['gender']));
}

/*Verifica el correo electronico*/
if(empty($_POST['email'])){
    $errors[]='Verifique el campo de Correo Electrónico del participante';
}else{
    $coel=mysqli_real_escape_string($dbc, trim($_POST['email']));
}

/*and repeat the code above for all the input that you have in your form */

if(empty($errors)){
    $q="INSERT INTO participante(nombre, paterno, materno, genero, correo, fechadenac, procedencia, ocupacion, asistencia, fechareg) VALUES ('$fina','$appa','$apma','$gend','$coel','$dabi','$prov','$ocup','$assi',NOW())";
    $r=mysqli_query($dbc,$q);
    if($r){
        echo '
            <p>
                Nombre: <b>'.$_POST['first_name'].'</b><br />
                Apellido Paterno: <b>'.$_POST['ape_pat'].'</b><br />
                Apellido Materno: <b>'.$_POST['ape_mat'].'</b><br />
                Genero: <b>'.$_POST['gender'].'</b><br />
                Correo Electrónico: <b>'.$_POST['email'].'</b><br />
                Fecha de nacimiento: <b>'.$_POST['date'].'</b><br />
                Procedencia: <b>'.$_POST['provenance'].'</b><br />
                Ocupación: <b>'.$_POST['ocuppation'].'</b><br />
                ¿Asistió? <b>'.$_POST['assistance'].'</b><br />
            </p>
            ';          
    }else{
        echo '
            <h2><a>¡Error del Sistema!</a></h2>
            <p>
                El registro no pudo realizarse debido a un error del sistema. Disculpe los incovenientes.<br />
            </p>
            <p>
                Error: '.mysqli_error($dbc).'<br />
                Query: '.$q.'<br />
            </p>
        ';
    }
    mysqli_close($dbc);
    include ('inc/footer.html');
    exit();
}else{
    echo '
        <p>
            Revise que todo los campos hayan sido llenados correctamente.<br /> 
            Se encontraron los siguientes errores: <br />                           
    ';
    foreach ($errors as $msg) {
        echo " - $msg<br />\n";
    }
    echo '
        </p>
        <p>
            Ingrese los datos faltantes e intente de nuevo.
        </p>
    ';
}
mysqli_close($dbc);

}

A simple solution (using jQuery) would be:

$(document).ready(function () {
    $('input').each(function () {
        var $this = $(this);
        var err = $this.attr('id') + ' is required.';
        var errElem = $('<span />').text(err).css({'color': 'red', 'font-weight': 'bold'});
        if ($this.val().length === 0) {
            $this.parent('td').append(errElem);
        }
    });
});

Make sure to do server-side validation as well. There are some users who disable JavaScript (and then this wouldn't run).

Below is what I will have a normal html file

<html>
<head>
<script language="javascript">

function validateMe() {

if (firstname is blank) {
alert("Enter first name");
form.first.focus();
return false;
}

if (lastname is blank) {
alert("Enter last name");
form.last.focus();
return false;
}

return true;
}

</script>
<body>

// Form here

<input type="submit" name="submit" value="Submit" onClick="return validateMe()">

</body>
</html>

if first name is blank, form never submit the form...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM