Laravel注册表单上的自定义验证 [英] Laravel custom validation on registration form

查看:46
本文介绍了Laravel注册表单上的自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力对注册表进行验证.

I'm currently struggling with a bit of validation on a registration form.

基本上,当用户注册时,它将检查他们输入的唯一代码是否有效,如果无效,则不允许他们注册.

Basically when a user registers it will check if the unique code they have entered is valid and if not doesn't let them sign up.

但是在我从中读取的代码表中,代码上也有到期日.

But in my codes table which this reads from I also have an expiry date on the code.

在认为有效期限尚未过去之后,我需要再次进行检查,换句话说,它不大于现在.

I need to do another check after it is deemed valid that the expiry date hasn't passed, in other words it is not greater than now.

我认为您可以在验证器中执行此操作,但是我在语法上有些挣扎,不确定应该去哪里.这是我的代码:

I think you can do this in the validator but I'm struggling a bit with the syntax and not sure where it should go. Here is my code:

protected function validator(array $data)
{

    return Validator::make($data, [
        'code' => 'required|exists:codes',
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'date_of_birth' => 'required|date',
        'password' => 'required|min:6|confirmed',
        'accept_terms' => 'required|accepted',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{   
    Code::where('code', $data['code'])->increment('uses');

    $data['code_id'] = Code::where('code', $data['code'])->value('id');

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'date_of_birth' => $data['date_of_birth'],
        'accept_terms' => $data['accept_terms'],
        'code' => $data['code'],
        'code_id' => $data['code_id'],
        'password' => bcrypt($data['password']),
    ]);
}

先谢谢您了:)

推荐答案

只要您使用的是Laravel v5.3.18(或更高版本),就可以使用 Rule 类来节省定义一个自定义规则.

As long as you're using Laravel v5.3.18 (or higher) you can use the Rule Class to save you having to define a custom rule.

此:

'code' => 'required|exists:codes',

可以替换为:

'code' => [
    'required',
    Rule::exists('codes')->where(function ($query) {
        $query->where('expiry_date', '>=', Carbon::now());
    }),
],

(以上假设 expiry_date 是您的数据库表中列的实际名称).

(the above is assuming expiry_date is the actual name of the column in your db table).

文档: https://laravel.com/docs/5.3/validation#rule-存在

只需确保您导入了这些立面即可.

Just make sure you import those facades.

希望这会有所帮助!

这篇关于Laravel注册表单上的自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆