提交前验证表单(检查是否输入了所有字段)


Validate form before submitted (Check all fields are entered)

在将下表插入数据库之前,我正在检查下表中的字段是否已填写。例如,显示一个包含未填写字段的弹出窗口。这只是一个简单的注册表。

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

如何使用JavaScript或jQuery来完成此操作。

首先,下载jQuery验证插件并将其添加到您的页面中。然后给每个想要使必填字段成为required类的输入。然后在jQuery中:

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

验证插件功能非常丰富,因此您可以根据需要显示不同类型的消息、不同的验证检查等。文档中有更多关于这方面的信息。

最后,与所有javascript前端验证一样,确保您也在服务器端验证用户输入,以防用户在浏览器中关闭javascript。

一个简单的解决方案(使用jQuery)是:

$(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);
        }
    });
});

确保也进行服务器端验证。有些用户禁用了JavaScript(这样就不会运行了)。

下面是我将拥有的普通html文件

<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($_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);

}