artgrosvil
@artgrosvil
#dev #programming #student #startups #chill

Почему form_validation не работает?

Здравствуйте. Использую фреймворк codeigniter, и его встроенный класс валидации формы. Так же на стороне frontend'а использую библиотеку jqueryvalidation.org. Без этой библиотеки валидация на стороне codeginiter работает, но вместе с ней нет.

Пример кода отправки с помощью ajax:
$('#button-l-p-auth').click(function() {
    $.ajax({
        url: '/auth/auth_user',
        dataType: "json",
        type: 'POST',
        data: $('form-l-p-auth').serialize(),
        success: function (response) {
            if (response.status == 'error') {
                $('#form-l-p-auth-response').empty();
                $('#form-l-p-auth-response').append(response.message);
            } else if(response.status == 'success') {
                window.location.href = response.redirect;
            }
        }
    });
});


Валидация:
$(document).ready(function () {
    $("#form-l-p-auth").validate({
        rules: {
            email: {
                required: true,
                minlength: 4
            },
            password: {
                required: true,
                minlength: 6
            },
        },
        messages: {
            email: {
                required: "This field can't be blank.",
                minlength: "Please enter a valid email address."
            },
            password: {
                required: "This field can't be blank.",
                minlength: "Password has to be 6 symbols min."
            },
        }
    });
});


Принимаю на сервере:
public function auth_user()
	{
		if ($this->form_validation->run()) {
			$email = $this->input->post('email');
			$password = $this->input->post('password');

			$data_user = $this->auth_model->get_data_user($email);
			if ($data_user->num_rows() > 0) {

				$data_user = $data_user->row();
				$hash_pass_tmp = crypt($password, $data_user->hash_pass);
				if ($data_user->hash_pass == $hash_pass_tmp) {
					$auth_data = array(
						'id' => $data_user->id,
						'email' => $data_user->email,
						'logged' => TRUE
					);
					$this->session->set_userdata($auth_data);
					$data = array(
						'status' => 'success',
						'redirect' => base_url('apps')
					);
					print(json_encode($data));
				} else {
					$data = array(
						'status' => 'error',
						'message' => 'Wrong password'
					);
					print(json_encode($data));
				}
			} else {
				$data = array(
					'status' => 'error',
					'message' => 'Unrecognised email'
				);
				print(json_encode($data));
			}
		} else {
			$data = array(
				'status' => 'error',
				'message' => 'This field can\'t be blank.'
			);
			print(json_encode($data));
		}
	}


Валидация на стороне сервера:
'auth/auth_user' => array(
		array(
			'field' => 'password',
			'label' => 'Password user',
			'rules' => 'trim|required|min_length[6]'
		),
		array(
			'field' => 'email',
			'label' => 'Email user',
			'rules' => 'trim|required|valid_email'
		)
	),


Форма отправки:
<form class="form-horizontal" id="form-l-p-auth" method="post" accept-charset="utf-8">
							<div class="form-group">
								<div class="col-lg-12">
									<input type="email" class="form-control" id="email" name="email"
									       placeholder="Email">
								</div>
							</div>
							<div class="form-group">
								<div class="col-lg-12">
									<input type="password" class="form-control" id="password" name="password"
									       placeholder="Password">
								</div>
							</div>
							<div class="form-group">
								<div class="col-lg-12 form-l-p-auth">
									<span id="form-l-p-auth-response"></span>
								</div>
							</div>
							<div class="form-group">
								<div class="col-lg-12">
									<button type="button" class="btn btn-success" id="button-l-p-auth">Submit</button>
								</div>
							</div>
						</form>


Еще не понятно почему, но по деббагеру хрома нет отправляемых данных:
3YV1nAV.png
Ошибку в ответе возвращает именно класс валидации codeigniter'а. Т.е. "This field can\'t be blank.". Ума не приложу почему.

Предполагаю, что неправильно или вообще не проходит сериализация данных с формы.
  • Вопрос задан
  • 242 просмотра
Решения вопроса 1
artgrosvil
@artgrosvil Автор вопроса
#dev #programming #student #startups #chill
Вопрос снят. Забыл # в отправке ajax запроса дописать к id формы.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы