Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add exclude validation rule #38537

Merged
merged 1 commit into from
Aug 25, 2021
Merged

[8.x] Add exclude validation rule #38537

merged 1 commit into from
Aug 25, 2021

Conversation

bastien-phi
Copy link
Contributor

This PR adds an exclude validation rule which exclude the field from validated data.

This validation

public function rules()
{
    return [
        'role' => ['required', in:user,guest'],
        'email' => [
            'required_if:role,user',
            'exclude_unless:role:user',
            'string',
            'email,
         ],
     ];
}

is quite easy but we need to take a close look to email validation.

We can take advantage of Rule::when for email field to make the validation quite easier to read :

public function rules()
{
    return [
        'role' => ['required', 'in:user,guest'],
        'email' => Rule::when(
            function ($data) => $data->get('role') === 'user',
            ['required', 'string', 'email'],
            'exclude'
       ),
   ];
}

This way, the validation is easier to read.

@taylorotwell taylorotwell merged commit 160c719 into laravel:8.x Aug 25, 2021
@bastien-phi
Copy link
Contributor Author

Thanks !

@bastien-phi bastien-phi deleted the add_exclude_validation_rule branch August 25, 2021 13:55
victorvilella pushed a commit to cdsistemas/framework that referenced this pull request Oct 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants