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

[11.x] Improve Email validation rule custom translation messages #54202

Merged

Conversation

SanderMuller
Copy link
Contributor

Via #54067 we introduced the fluent Email validation rule. While implementing this new feature in our project I noticed that the existing custom validation message was not being used.

This PR adds tests that test custom validation messages, and makes changes to the Email class to make the tests pass. This change also

This PR makes the following diff possible:

    public function rules(): array
    {
        return [
            'answer.email_address' => [
                'required',
                'string',
-                new class extends Email {
-                    public function message(): string
-                    {
-                        return __('check_answer.validation.email.invalid');
-                    }
-                },
+                Email::default(),
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'answer.email_address.required' => __('check_answer.validation.email.required'),
            'answer.email_address.string' => __('check_answer.validation.email.invalid'),
            'answer.email_address.email' => __('check_answer.validation.email.invalid'),
        ];
    }

The Email class is quite some slimmer due to now converting to the old rules and then validating that, instead of implementing the different email validation classes. This way the email specific validation and the customRules can just be merged, similar to how the File rule works.

The ValidationEmailRuleTest (and ValidationPasswordRuleTest and ValidationFileRuleTest) are quite confusing, the helper methods are nice for simple tests, but complex tests/cases result in cognitive overload. I would be happy to see if we can simplify these tests, and also test more cases, e.g. the other existing rules don't test custom validation messages.

The implementation of the messages() method in the different Rule classes in Illuminate\Validation\Rules also differ to a confusing extend. Let me know if you are open to receiving follow-up PRs to cleanup the framework in this area.

@taylorotwell taylorotwell merged commit 4ddd68e into laravel:11.x Jan 15, 2025
38 checks passed
@SanderMuller SanderMuller deleted the fix-fluent-rule-custom-messages branch January 15, 2025 22:45
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