逐个验证表单的字段

时间:2013-11-19 19:02:22

标签: javascript php ajax html5 forms

我有一个包含7个字段的表单。当我将其提交到“register.php”页面时,它将逐个处理每个字段并输出结果。但这将整体输出结果。但我需要使用ajax验证数据并逐个收集输出,并在离开现场时将其显示给用户。

经过此验证后,我还需要通过一次点击发送所有字段;使用提交按钮。

html文件

<form action="register.php" method="post" class="ajax">
        <ul>
            <li>Username*:<br> <input type="text" name="username" required></li>
            <li>Password*:<br> <input type="password" name="password" required></li>
            <li>Confirm the Password*:<br> <input type="password" name="password_again" required></li>
            <li>First Name*:<br> <input type="text" name="first_name" required></li>
            <li>Last Name:<br> <input type="text" name="last_name"></li>
            <li>Email*:<br> <input type="text" name="email" required></li>
            <li><input type="submit" value="Register"></li>
        </ul>
    </form>

register.js文件

$('form.ajax').on('submit',function(){
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

that.find('[name]').each(function(index,value){
    var that =$(this),
        name =that.attr('name'),
        value = that.val();
        data[name] = value;
}); 

$.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
        document.getElementById("demo").innerHTML= response;

    }
});

return false;

});

我的php文件:

     if (empty($errors)=== TRUE) {
     if (user_exists($_POST['username'])=== TRUE) {
         $errors[] = 'Sorry, the Username \''. $_POST['username'] . '\' is already in use';
     }

     if (preg_match("/\\s/", $_POST['username'])== TRUE) {
         $errors[] = 'Username must not contain any spaces';
     }

     if (strlen($_POST['password']) < 6) {
         $errors[] = 'Your password must be at least 6 characters';
     }  

     if ($_POST['password'] !== $_POST['password_again']) {
         $errors[] = 'Passwords do not match';
     }  

     if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)=== FALSE) {
         $errors[] = 'Invalid email address';
     }

     if (email_exists($_POST['email']) === TRUE) {
         $errors[] = 'Sorry, the email address \''. $_POST['email'] . '\' is already in use';
     }

 }
 }


if (isset($_GET['success']) && empty($_GET['success'])) {
    echo "You've been registered successfully!";
}
else{

    if (empty($_POST)=== FALSE && empty($errors) === TRUE) {

        $register_data = array(
            'username'  => $_POST['username'],
            'password'  => $_POST['password'],
            'first_name'=> $_POST['first_name'],
            'last_name' => $_POST['last_name'],
            'email'     => $_POST['email'],
        );
        register_user($register_data);
        header('Location: register.php?success');
        exit();
    }else if(empty($errors)=== FALSE){

1 个答案:

答案 0 :(得分:0)

我没有以任何方式对此进行测试,但它应该可行。我为每个必需的表单元素分配了一个validated属性,在输入模糊时将它们验证到服务器,然后在提交表单之前检查没有任何未经验证的元素。

var $form = $('form.ajax'),
    $fields = $form.find('input[required]');

$fields.attr('validated', false).on('blur', function(){
    var $this = $(this);
    if($this.val() != ''){
        var payload = {};
            // create name=value object to post to server
        payload[$this.attr('name')] = $this.val();
        $.ajax({
            url: $form.attr('action'),
            data: payload,
                    method: 'POST',
            success: function(response){
                if(response.valid) { // or whatever
                    $this.attr('validated', true);
                }
            }
        })
    }
})

$form.on('submit', function(){
    if($this.find('input[validated=false]')){
        return false;
    }
    return true;
})