php Laravel 验证属性“好名字”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17047116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel validation attributes "nice names"
提问by Hak
I'm trying to use the validation attributes in "language > {language} > validation.php", to replace the :attribute name (input name) for a proper to read name (example: first_name > First name) . It seems very simple to use, but the validator doesn't show the "nice names".
我正在尝试使用 "language > {language} > validation.php" 中的验证属性,将 :attribute name (input name) 替换为正确的读取名称 (example: first_name > First name) 。使用起来似乎很简单,但验证器没有显示“好名字”。
I have this:
我有这个:
'attributes' => array(
'first_name' => 'voornaam'
, 'first name' => 'voornaam'
, 'firstname' => 'voornaam'
);
For showing the errors:
用于显示错误:
@if($errors->has())
<ul>
@foreach ($errors->all() as $error)
<li class="help-inline errorColor">{{ $error }}</li>
@endforeach
</ul>
@endif
And the validation in the controller:
以及控制器中的验证:
$validation = Validator::make($input, $rules, $messages);
The $messages array:
$messages 数组:
$messages = array(
'required' => ':attribute is verplicht.'
, 'email' => ':attribute is geen geldig e-mail adres.'
, 'min' => ':attribute moet minimaal :min karakters bevatten.'
, 'numeric' => ':attribute mag alleen cijfers bevatten.'
, 'url' => ':attribute moet een valide url zijn.'
, 'unique' => ':attribute moet uniek zijn.'
, 'max' => ':attribute mag maximaal :max zijn.'
, 'mimes' => ':attribute moet een :mimes bestand zijn.'
, 'numeric' => ':attribute is geen geldig getal.'
, 'size' => ':attribute is te groot of bevat te veel karakters.'
);
Can someone tell me what i'm doing wrong. I want the :attribute name to be replaced by the "nice name" in the attributes array (language).
有人可以告诉我我做错了什么。我希望将 :attribute 名称替换为属性数组(语言)中的“不错的名称”。
Thanks!
谢谢!
EDIT:
编辑:
I noticed that the problem is I never set a default language for my Laravel projects. When I set the language to 'NL' the code above works. But, when I set my language, the language will appear in the url. And I prefer it doesn't.
我注意到问题是我从来没有为我的 Laravel 项目设置默认语言。当我将语言设置为“NL”时,上面的代码有效。但是,当我设置语言时,该语言将出现在 url 中。我更喜欢它没有。
So my next question: Is it possible to remove the language from the url, or set the default language so it just doesn't appear there?
所以我的下一个问题:是否可以从 url 中删除语言,或设置默认语言使其不出现在那里?
回答by Javier Cadiz
Yeahh, the "nice name" attributes as you called it was a real "issue" a few month ago. Hopefully this feature is now implementedand is very simply to use.
是的,几个月前你所说的“好名字”属性是一个真正的“问题”。希望这个功能现在已经实现并且使用起来非常简单。
For simplicity i will split the two options to tackle this problem:
为简单起见,我将拆分两个选项来解决这个问题:
GlobalProbably the more widespread. This approach is very well explained herebut basically you need to edit the application/language/XX/validation.phpvalidation file where XX is the language you will use for the validation.
At the bottom you will see an attribute array; that will be your "nice name" attributes array. Following your example the final result will be something like this.
'attributes' => array('first_name' => 'First Name')
LocallyThis is what Taylor Otwell was talking about in the issuewhen he says:
You may call setAttributeNames on a Validator instance now.
That's perfectly valid and if you check the source codeyou will see
public function setAttributeNames(array $attributes) { $this->customAttributes = $attributes; return $this; }
So, to use this way see the following straightforward example:
$niceNames = array( 'first_name' => 'First Name' ); $validator = Validator::make(Input::all(), $rules); $validator->setAttributeNames($niceNames);
全球可能更普遍。这种方法在这里得到了很好的解释,但基本上您需要编辑application/language/XX/validation.php验证文件,其中 XX 是您将用于验证的语言。
在底部你会看到一个属性数组;这将是您的“好名字”属性数组。按照您的示例,最终结果将是这样的。
'attributes' => array('first_name' => 'First Name')
本地这就是 Taylor Otwell 在这个问题上所说的:
您现在可以在 Validator 实例上调用 setAttributeNames。
这是完全有效的,如果您检查源代码,您会看到
public function setAttributeNames(array $attributes) { $this->customAttributes = $attributes; return $this; }
因此,要使用这种方式,请参阅以下简单示例:
$niceNames = array( 'first_name' => 'First Name' ); $validator = Validator::make(Input::all(), $rules); $validator->setAttributeNames($niceNames);
Resources
资源
There is a really awesome repo on Githubthat have a lot of languages packages ready to go. Definitely you should check it out.
Github上有一个非常棒的 repo,其中有很多语言包可供使用。绝对你应该检查一下。
Hope this helps.
希望这可以帮助。
回答by Logus
The correct answer to this particular problem would be to go to your app/langfolder and edit the validation.phpfile at the bottom of the file there is an array called attributes:
这个特定问题的正确答案是转到您的app/lang文件夹并编辑文件底部的validation.php文件,其中有一个名为attributes的数组:
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => array(
'username' => 'The name of the user',
'image_id' => 'The related image' // if it's a relation
),
So I believe this array was built to customise specifically these attribute names.
所以我相信这个数组是专门为自定义这些属性名称而构建的。
回答by ShirleyCC
Since Laravel 5.2 you could...
从 Laravel 5.2 开始,你可以...
public function validForm(\Illuminate\Http\Request $request)
{
$rules = [
'first_name' => 'max:130'
];
$niceNames = [
'first_name' => 'First Name'
];
$this->validate($request, $rules, [], $niceNames);
// correct validation
回答by Altrim
In the "attributes" array the key is the input name and the value is the string you want to show in the message.
在“属性”数组中,键是输入名称,值是要在消息中显示的字符串。
An example if you have an input like this
一个例子,如果你有这样的输入
<input id="first-name" name="first-name" type="text" value="">
The array (in the validation.php file) should be
数组(在validation.php 文件中)应该是
'attributes' => array(
'first-name' => 'Voornaam'),
I tried the same thing and it works great. Hope this helps.
我尝试了同样的事情,效果很好。希望这可以帮助。
EDIT
编辑
Also I am noticing you don't pass a parameter to $errors->has()
so maybe that's the problem.
另外我注意到你没有传递参数,$errors->has()
所以也许这就是问题所在。
To fix this check out in the controller if you have a code like this
如果您有这样的代码,请在控制器中解决此问题
return Redirect::route('page')->withErrors(array('register' => $validator));
then you have to pass to the has()
method the "register" key (or whatever you are using) like this
然后你必须has()
像这样将“注册”键(或你正在使用的任何东西)传递给方法
@if($errors->has('register')
.... //code here
@endif
Another way to display error messages is the following one which I prefer (I use Twitter Bootstrap for the design but of course you can change those with your own design)
显示错误消息的另一种方式是以下我更喜欢的方式(我使用 Twitter Bootstrap 进行设计,但当然您可以使用自己的设计更改它们)
@if (isset($errors) and count($errors->all()) > 0)
<div class="alert alert-error">
<h4 class="alert-heading">Problem!</h4>
<ul>
@foreach ($errors->all('<li>:message</li>') as $message)
{{ $message }}
@endforeach
</ul>
</div>
回答by Jan Schwingneschl?gl
I use my custom language filesas Input for the "nice names"like this:
我使用我的自定义语言文件作为“好名字”的输入,如下所示:
$validator = Validator::make(Input::all(), $rules);
$customLanguageFile = strtolower(class_basename(get_class($this)));
// translate attributes
if(Lang::has($customLanguageFile)) {
$validator->setAttributeNames($customLanguageFile);
}
回答by John Smith
In Laravel 4.1 the easy way to do this is go to the lang folder -> your language(default en) -> validation.php.
在 Laravel 4.1 中,最简单的方法是转到 lang 文件夹 -> 您的语言(默认为 en) -> validation.php。
When you have this in your model, for example:
当你的模型中有这个时,例如:
'group_id' => 'Integer|required',
'adult_id' => 'Integer|required',
And you do not want the error to be "please enter a group id", you can create "nice" validation messages by adding a custom array in validation.php. So in our example, the custom array would look like this:
并且您不希望错误为“请输入组 ID”,您可以通过在 validation.php 中添加自定义数组来创建“不错”的验证消息。因此,在我们的示例中,自定义数组将如下所示:
'custom' => array(
'adult_id' => array(
'required' => 'Please choose some parents!',
),
'group_id' => array(
'required' => 'Please choose a group or choose temp!',
),
),
This also works with multi-language apps, you just need to edit (create) the correct language validation file.
这也适用于多语言应用程序,您只需要编辑(创建)正确的语言验证文件。
The default language is stored in the app/config/app.php configuration file, and is English by default.
This can be changed at any time using the App::setLocale
method.
默认语言存储在 app/config/app.php 配置文件中,默认为英文。这可以使用该App::setLocale
方法随时更改。
More info to both errors and languages can be found here validationand localization.
回答by Alexandre Danault
The :attribute can only use the attribute name (first_name in your case), not nice names.
:attribute 只能使用属性名称(在您的情况下为 first_name),而不是好的名称。
But you can define custom messages for each attribute+validation by definine messages like this:
但是您可以通过定义如下消息为每个属性+验证定义自定义消息:
$messages = array(
'first_name_required' => 'Please supply your first name',
'last_name_required' => 'Please supply your last name',
'email_required' => 'We need to know your e-mail address!',
'email_email' => 'Invalid e-mail address!',
);
回答by Wahyu Kodar
In Laravel 7.
在 Laravel 7.
use Illuminate\Support\Facades\Validator;
Then define niceNames
然后定义 niceNames
$niceNames = array(
'name' => 'Name',
);
And the last, just put $niceNames in fourth parameter, like this:
最后,只需将 $niceNames 放在第四个参数中,如下所示:
$validator = Validator::make($request->all(), $rules, $messages, $niceNames);
回答by Victor Moura
Well, it's quite an old question but I few I should point that problem of having the language appearing at the URL can be solved by:
嗯,这是一个很老的问题,但我应该指出,在 URL 中出现语言的问题可以通过以下方式解决:
- Changing the language and fallback_language at
config/app.php
; - or by setting \App::setLocale($lang)
- 更改语言和 fallback_language
config/app.php
; - 或通过设置 \App::setLocale($lang)
If needed to persist it through session, I currently use the "AppServiceProvider" to do this, but, I think a middleware might be a better approach if changing the language by URL is needed, so, I do like this at my provider:
如果需要通过会话保持它,我目前使用“AppServiceProvider”来执行此操作,但是,如果需要通过 URL 更改语言,我认为中间件可能是更好的方法,因此,我在我的提供程序中这样做:
if(!Session::has('locale'))
{
$locale = MyLocaleService::whatLocaleShouldIUse();
Session::put('locale', $locale);
}
\App::setLocale(Session::get('locale'));
This way I handle the session and it don't stick at my url.
这样我就可以处理会话并且它不会停留在我的网址上。
To clarify I'm currently using Laravel 5.1+ but shouldn't be a different behavior from 4.x;
澄清一下,我目前使用的是 Laravel 5.1+,但不应与 4.x 有不同的行为;