Laravel自定义验证消息参数 [英] Laravel custom validation message parameter

查看:306
本文介绍了Laravel自定义验证消息参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel 5.1.我有一个summernotejs表单元素.我已经成功创建了一个自定义验证规则,该规则将从表单输入中获取HTML,剥离标签,并对文本内容进行strlen()调用.因此,我可以看到一条没有任何标签的消息的长度.

I'm using laravel 5.1. I have a summernotejs form element. I've created a custom validation rule successfully, which takes the HTML provided from the form input, strips the tags, and does a strlen() call on the text content. Therefore I can see the length of a message without any tags in it.

这是我的验证规则:

Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {
    return strlen(strip_tags($value)) >= $parameters[0];
});

我通过指定以下内容来调用验证规则:strip_min:10strip_min:20等,数字是剥离标签后的最小字符串长度.

I call the validation rule by specifying: strip_min:10 or strip_min:20 etc, with the number being the minimum string length after stripping tags.

我想添加一条自定义消息,说内容长度必须至少为n个字符.

I want to add a custom message, saying that the content lengths needs to be a minimum of n characters long.

Laravel文档在这方面是没有用的.我已经打开了validation.php文件,其中包含所有错误消息.

The Laravel documentation on this aspect is useless. I've opened my validation.php file, which contains all the error messages.

我已将键strip_min添加到消息数组中,并显示消息:The :attribute must be at least :min characters.

I've added the key strip_min to the message array, with the message: The :attribute must be at least :min characters.

测试时,我收到错误消息:

When I test it, I get the error message:

The notice must be at least :min characters.

如何将:min转换为验证规则中指定的数字?我已经阅读了文档,但是到处都是,我无法理解如何仅用给定的数字替换:min.

How can I convert :min into the number specified in the validation rule?! I've read the documentation but it's all over the place, and I cant understand how to just simply replace :min with the given number.

推荐答案

发现了.

Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {

    $validator->addReplacer('strip_min', function($message, $attribute, $rule, $parameters){
        return str_replace([':min'], $parameters, $message);
    });

    return strlen(strip_tags($value)) >= $parameters[0];
});

这篇关于Laravel自定义验证消息参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆