Skip to content

[Validator] Allow to define a reusable set of constraints #34334

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

Merged
merged 1 commit into from
Feb 8, 2020
Merged

[Validator] Allow to define a reusable set of constraints #34334

merged 1 commit into from
Feb 8, 2020

Conversation

ogizanagi
Copy link
Contributor

Q A
Branch? 5.1
Bug fix? no
New feature? yes
Deprecations? no
Tickets N/A
License MIT
Doc PR TODO

The goal of this feature is to simplify writing a set of validation constraints to be reused consistently across the application. Which is especially useful with DTOs, as a same set of constraints can be used in different places.

For instance, given multiple DTOs containing the new user password in for different use-cases (register, forgot pwd, change pwd), the same rules apply on the property. Hence with this PR, you can write a single constraint class to be reused:

/**
 * @Annotation
 */
class MatchesPasswordRequirements extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new NotBlank(),
            new Type('string'),
            new Length(['min' => 12]),
            new NotCompromisedPassword(),
        ];
    }
}

I'm open to better naming and ways to expose the options to the Compound::getConstraints method, so options can be forwarded to the nested constraints for most specific use-cases.

@nicolas-grekas
Copy link
Member

(rebase needed, then ready, right?)

@ogizanagi
Copy link
Contributor Author

Rebased & ready to me

@fabpot
Copy link
Member

fabpot commented Feb 8, 2020

Thank you @ogizanagi.

@fabpot fabpot closed this in f53ea3d Feb 8, 2020
@fabpot fabpot merged commit 8f1b0df into symfony:master Feb 8, 2020
@ogizanagi ogizanagi deleted the validator_compound_constraint branch February 8, 2020 08:42
@nicolas-grekas nicolas-grekas modified the milestones: next, 5.1 May 4, 2020
@fabpot fabpot mentioned this pull request May 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants