codeigniter 仅在CI4上提交数据后运行验证

yebdmbv4  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(168)

我使用CI4和引导程序创建了登录表单,但表单在数据输入前总是显示验证错误,我已在视图文件中添加了is-invalid逻辑。

这里是我的控制器代码

$session = session();
if ($session->get('email')) {
    if ($session->get('role_id') == 1) {
        return redirect()->to('/');
    } else {
        return redirect()->to('/');
    }
}
$isValid = $this->validate([
    'email' => 'required|trim|valid_email',
    'password' => 'required|trim'
]);
if (!$isValid) {
    $data['title'] = 'Login';
    echo view('template/auth_header', $data);
    echo view('auth/login', ['validation' => $this->validator]);
    echo view('template/auth_footer');
} else {
    $this->_login();
}

这是我的登录视图

<form class="user" method="post" action="<?= base_url('auth/login') ?>">
    <div class="form-group">
        <input type="text" class="form-control form-control-user <?= ($validation->hasError('email')) ? 'is-invalid' : ''; ?>" id="email" placeholder="Enter Email Address..." name="email" value="<?= set_value('email'); ?>">
        <div class="invalid-feedback">
            <?= $validation->getError('email'); ?>
        </div>
    </div>
    <div class="form-group">
        <input type="password" class="form-control form-control-user <?= ($validation->hasError('password')) ? 'is-invalid' : ''; ?>" id="password" placeholder="Password" name="password">
        <div class="invalid-feedback">
            <?= $validation->getError('password'); ?>
        </div>
    </div>
    <button type="submit" class="btn btn-primary btn-user btn-block">
        Login
    </button>
</form>
w6mmgewl

w6mmgewl1#

您只需要在提交表单时发送错误,否则请清除验证程序并加载视图,下面是一个示例,希望这样可以消除这种混淆

$session = session();
if ($session->get('email')) {
    if ($session->get('role_id') == 1) {
        return redirect()->to('/');
    } else {
        return redirect()->to('/');
    }
}
$this->validate([
    'email' => 'required|trim|valid_email',
    'password' => 'required|trim'
]);

if ($this->validate->withRequest($this->request)->run() == false) {

    if ($this->request->getMethod() === 'post') {
        $data["validation"] = $this->validator;
        return redirect()->back()->withInput()->with('errors', $this->validate->getErrors());
    } else {
        $this->validate->reset();
        $data['title'] = 'Login';
        echo view('template/auth_header', $data);
        echo view('auth/login', ['validation' => $this->validator]);
        echo view('template/auth_footer');
    }
} else {
    $this->_login();
}

相关问题