我在AppServiceProvider @ boot中定义了一个自定义验证器,如下所示
0CE0++Kn9mi5xd7nAz/mWOrr7939RWwzfxhBzxAWtAk=
问题是验证者的实例无法访问/* Custom unique value in set of fields validation */
Validator::extend('unique_in', function ($attribute, $value, $parameters, $validator) {
$validator_data = $validator->getData();
foreach ($parameters as $field) {
if ($value === array_get($validator_data, $field)) {
return false;
}
}
return true;
}, 'The :attribute cannot be same as any other field in this form.');
/* replace the :fields message string */
Validator::replacer('unique_in', function ($message, $attribute, $rule, $parameters) {
// I was doing this (this works)
// $message = str_replace(':field', implode(',',$parameters), $message);
// return $message;
//I want to do this (to get proper names for the fields)
$other = $this->getAttribute(array_shift($parameters));
return str_replace([':other', ':values'], [$other, implode(', ', $parameters)], $message);
});
。
getAttribute解析参数的可读名称
是否可以在replacer中访问验证器实例?
请注意getAttribute
中的闭包有Validator::extend
,它是验证者的一个实例。
答案 0 :(得分:0)
我使用getCustomMessage
和setCustomMessage
工作了,但没有单独使用Validator::replacer
使用Validator::extend
。
Validator::extend('unique_in', function ($attribute, $value, $parameters, $validator) {
$validator_data = $validator->getData();
$parameters = array_diff($parameters, [$attribute]);
$same = null;
$other = null;
foreach ($parameters as $field) {
if ($value === array_get($validator_data, $field)) {
$same[] = $field;
}
}
//No same values found , validation success
if (is_null($same)) {
return true;
}
// Get all Custom Attributes those are defined for this validator and replace with field in $same array and create a new $other array
$custom_attributes = $validator->getCustomAttributes();
foreach ($same as $attribute) {
$other[$attribute] = isset($custom_attributes[$attribute]) ? $custom_attributes[$attribute] : $attribute;
}
//Task of Validator:replacer is done right here.
$message = 'The :attribute cannot have same value ":value" as in :fields';
$message = str_replace([':value',':fields'], [$value ,implode(', ', $other)], $message);
$validator->setCustomMessages(array_merge($validator->getCustomMessages(), ['unique_in' => $message]));
return false;
});
谢谢,
ķ
答案 1 :(得分:0)
我知道这有点陈旧且已经回答了帖子,但是我在搜索这个问题的答案时遇到的第一个。
我想分享我的解决方案。我在Validator :: replacer闭包中使用了与Laravel 5.4的Localization,如下所示:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="root">
<assets>
<xsl:apply-templates/>
</assets>
</xsl:template>
<xsl:template match="items | metadata">
<xsl:apply-templates/>
</xsl:template>
</xsl:transform>
答案 2 :(得分:0)
使用trans()。你可以这样做:
Validator::replacer('greater_than', function($message, $attribute, $rule, $parameters) {
return str_replace(':field', trans('validation.attributes.'.$parameters[0]), $message);
});