简体   繁体   中英

Apply several constraints in one “validate” pass in Silex

I'm using Silex, and trying to validate some value with validator service. But the problem is that I need apply several constraints to one value, but validator don't let to do this without using Required constraint.

When I just want to validate a choice value (say, 'apple' or 'orange') I have to wrap constraints Choice and NotNull (because Choice allows a null value) into Required and Collection (because Required cannot be used without Collection and it is CollectionValidator who validates series of Required 's constraints) like this:

$violations = $app['validator']->validate(array('value'), 
    new Collection(array(
        new Required(array(
            new Choice(array('apple', 'orange')),
            new NotNull()
        ))
    )));

It looks verbose so I'm looking for more elegant solution (for such explicit use of validator).

You can use the validateValue function that accepts an array of constraints as second parameter.

$violations = $app['validator']->validateValue('value', array(
    new Choice(array('apple', 'orange')),
    new NotBlank()
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM