【问题标题】:Respect Validation php slim custom messages尊重验证 php slim 自定义消息
【发布时间】:2019-10-16 01:23:40
【问题描述】:

我已阅读文档,我想知道是否可以根据规则和属性制作自定义消息,例如我有以下代码

 $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

有什么办法吗?

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 简单而优雅的答案,比我做的要好得多,我将在下一个项目中使用它
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 2016-02-29
    • 2013-06-05
    • 2012-12-12
    • 2013-01-08
    • 2019-07-04
    相关资源
    最近更新 更多