在laravel中简单地验证电子邮件,而无需创建验证器

neekobn8  于 2023-10-22  发布在  其他
关注(0)|答案(4)|浏览(175)

如何在laravel中简单地验证电子邮件,而不创建验证器?

Validator::email($email)

不起作用

5vf7fwbs

5vf7fwbs1#

如何使用PHP filter_var
https://www.php.net/manual/en/filter.filters.validate.php

filter_var($email, FILTER_VALIDATE_EMAIL)
q1qsirdb

q1qsirdb2#

Laravel使用egulias/email-validator包来验证电子邮件。因此,您可以在不创建验证器示例的情况下使用它。举例来说:

use Egulias\EmailValidator\EmailValidator;
    use Egulias\EmailValidator\Validation\DNSCheckValidation;
    use Egulias\EmailValidator\Validation\Extra\SpoofCheckValidation;
    use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
    use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
    use Egulias\EmailValidator\Validation\RFCValidation;

    //...

    $email = "[email protected]";

    //choose validators you want here
    $validations = [
        new NoRFCWarningsValidation(), //strict
        new DNSCheckValidation(), //dns
        new SpoofCheckValidation(), //spoof
        new FilterEmailValidation(), //filter
        FilterEmailValidation::unicode(), //filter_unicode,
        new RFCValidation(), //rfc
    ];

    $isValid = (new EmailValidator)->isValid($email, new MultipleValidationWithAnd($validations));

原始的Laravel 10电子邮件验证代码位于Illuminate\Validation\Concerns\ValidatesAttributes::validateEmail()

olhwl3o2

olhwl3o23#

By laravel ref
我们可以这样做Validator::make(['email' => $email], [ 'email' => 'email'])

通过使用laravel helper,我们可以这样做

validator(['email' => $email], ['email' => 'required|email']);

编辑:我们可以通过使用宏来进一步简化这一点
在服务提供商中添加此内容

$this
            ->app
            ->make(Validator::class)
            ->macro('email', function ($email) {
                return Validator::make(['email' => $email], [ 'email' => 'email'])
            });

现在我们可以像这样

Validator::email($email)

注:不是测试这个只是抛出一些想法,我们可以这样做。

nnvyjq4y

nnvyjq4y4#

BaseController使用ValidatesRequests trait,所以在控制器中你可以做.

public function store(Request $request)
{
$this->validate($request, [
    'email' => 'email',
]);
//
}

相关问题