尊重验证php slim自定义消息

时间:2019-05-30 11:24:52

标签: php validation slim slim-3 respect-validation

我已经阅读了文档,不知道是否可以根据规则AND属性创建自定义消息,例如,我有以下代码

 $casoValidator =  Validator::attribute('nombre',Validator::allOf(Validator::stringType(),Validator::notOptional(),
     Validator::stringType()->length(3,100))) //nombre, validamos que sea cadena, que es obligatorio y que tiene de 3 a 100 caracteres 
    ->attribute('idUsuario',Validator::allOf(Validator::intType())) 
    ->attribute('numeroSertel',Validator::allOf(Validator::stringType(), Validator::stringType()->length(1,100)))
    ->attribute('dni',Validator::allOf(Validator::stringType(), Validator::stringType()->length(8,20)));                                                                  //la capturaremos al hacer insert si hay problemas con las FK


        try {
            $asuntoValidator->assert($asunto);

        } catch(NestedValidationException $exception) {
            $errors = $exception->findMessages([
                'length' => '{{name}} no puede tener mas de 100 caracteres ni menos de uno',
                'notOptional' => '{{name}} no es opcional',
      .... 

如您所见,“ nombre”和“ dni”的长度不同,因此我应该返回两种不同的消息, 您的字符数不能少于3个,也不能超过100个 对于dni,我应该返回dni不能少于8个字符或不超过20个字符

有办法吗?

1 个答案:

答案 0 :(得分:1)

为自定义模板所需的每个规则添加一个单独的setTemplate方法调用。例如:

    $rule = v::key('color', v::alnum()->setTemplate('{{name}} must be alphanumeric value, for ex. f7f1d5'))
        ->key('color', v::length(6,6)->setTemplate('{{name}} must be a 6-character value'));


    $params['color'] = '¯\_(ツ)_/¯';

    try{
        $rule->assert($params);
    } catch (NestedValidationException $e) {
        $errors = $e->getMessages();
    }

    var_dump($errors);

结果:

array (size=2)
0 => string 'color must be alphanumeric value, for ex. f7f1d5' (length=48)
1 => string 'color must be a 6-character value' (length=33)
相关问题