使用Ajax / jQuery验证表单进行表单复制

时间:2013-07-09 01:48:01

标签: php validation jquery

最近我一直在学习AJAX和jQuery,以验证我的表单,而不是在刷新时使用验证。我有AJAX正式工作的表单提交 - 成功发送表单而没有页面刷新 - 但是当提交表单并通过User.php中的验证时,如果返回任何错误,这些将以单独的形式显示,而不是提交数据的原始表格。

编辑:错误一直在继续 - “implode(',',$ error)”有效,但我发现它在chrome中不起作用。我确信有一个快速解决方案,但我似乎无法找到一个有效。

create.ctp

    <?php echo $this->Html->script('jquery', FALSE); ?>
    <?php echo $this->Html->script('validation', FALSE); ?>
    <div id="success"></div>
    <div class="users form">
        <h2>Create User</h2>
    <?php echo $this->Form->create('User'); ?>
<fieldset>
<?php
    echo $this->Form->input('username', array('id'=>'username'));
    echo $this->Form->input('password', array('id'=>'password'));
            echo $this->Form->input('confirmpw', array('label'=>'Confirm Password', 'id'=>'confirmpw', 'type'=>'password'));
            echo $this->Form->input('tos', array('type'=>'checkbox', 'id'=>'tos', 'label' 
                =>__('I confirm I have read the Terms and Conditions', true), 'hidden'=>false, 'value'=>'yes'));
    ?>
</fieldset>
    <?php 

    echo $this->Js->submit('Send', array(
        'before'=>$this->Js->get('#sending')->effect('fadeIn'),
        'success'=>$this->Js->get('#sending')->effect('fadeOut'),
        'update'=>'#success'
    ));
    echo $this->Form->end();
    ?>
        <div id="sending" style="display: none; background-color: lightblue;">Sending...</div>
<?php 

?>
    </div>

validation.js

    $(document).ready(function() {
$('#username').blur(function(){
    $.post(
        '/practice/Users/validate_form',
        { field: $('#username').attr('id'), value: $('#username').val() },
        handleUsernameValidation
    );
});

function handleUsernameValidation(error) {
    if (error.length > 0) {
        if ($('#username-notEmpty').length == 0) {
            $('#username').after('<div id="username-notEmpty" class="error-message">' + error + "</div>");
        }
    }
    else {
        $('#username-notEmpty').remove();
    }
}
}
)

UsersController.php

        public function create() {
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            if ($this->RequestHandler->isAjax()) {
                $this->render('/Messages/success', 'ajax');
            }
            else {
            $this->Session->setFlash(__('The user has been saved'));
            $this->redirect(array('action' => 'index'));
            }
        }
    }
}

        public function validate_form() {
    if ($this->RequestHandler->isAjax()) {
        $field = $this->request->data['field'];
        $value = $this->request->data['value'];
        $this->request->data['User'][$field] = $value;
        $this->User->set($this->request->data);
        if ($this->User->validates()) {
            $this->autoRender = FALSE;
        }
        else {
            $error = $this->validateErrors($this->User);
            $this->set('error', $error[$this->request->data['field']]);
        }
    }
}

validate_form.ctp

    <?php echo implode(',', $error); ?>

user.php的

public $validate = array(
    'username' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Field cannot be empty.',
            'allowEmpty' => false,
            'required' => true,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'alphanumeric' => array(
            'rule' => array('alphanumeric'),
            'message' => 'Only alphanumeric characters allowed.',
            'allowEmpty' => false,
            'required' => true,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'maxlength' => array(
            'rule' => array('maxlength', '15'),
            'message' => 'Login name limit is 15 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'minlength' => array(
            'rule' => array('minlength', '6'),
            'message' => 'Login name must be more than 6 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
                    'isUnique' => array(
                            'rule' => array('isUnique'),
                            'message' => 'This username is not available, please pick a different name.',
                    ),
    ),
    'password' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Field cannot be empty.',
            'allowEmpty' => false,
            'required' => true,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
                'maxlength' => array(
            'rule' => array('maxlength', '15'),
            'message' => 'Password limit is 15 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'minlength' => array(
            'rule' => array('minlength', '6'),
            'message' => 'Password must be more than 6 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),

    ),
            'confirmpw' => array(
                'maxlength' => array(
            'rule' => array('maxlength', '15'),
            'message' => 'Password limit is 15 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'minlength' => array(
            'rule' => array('minlength', '6'),
            'message' => 'Password must be more than 6 characters.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
                    ),
                    'notEmpty' => array(
                            'rule' => array('notempty'),
                            'message' => 'Passwords do not match, please try again.'
                    ),
                    'equalToField' => array(
                        'rule' => array('equalToField', 'password'),
                        'message' => 'Passwords do not match, please try again.',
                        //'allowEmpty' => false,
                        //'required' => false,
                        //'last' => false, // Stop validation after this rule
                        'on' => 'create', //Limit validation to 'create' or 'update' operations
                    )
            ),

    'tos' => array(
                'comparison' => array(
                    'rule' => array('comparison', '==', 'yes'),
                    'required' => true,
                    'message' => 'Please agree to the Terms and Conditions.'
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
             ),
);

    function equalToField($check, $otherfield) {
        $fname = '';
        foreach ($check as $key => $value) {
            $fname = $key;
            break;
        }
        return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
    }

感谢。

1 个答案:

答案 0 :(得分:0)

据我所知,validateErrors返回了每个字段的错误消息数组。

你可以在validate_form.ctp

中试试
<?php echo implode(',', $error); ?>

如果不起作用,试试吧

<?php echo var_export($error); ?>

并查看$ error包含的变量类型。