Laravel只验证被张贴的项目,而忽略验证阵列的休息 [英] Laravel only validate items that are posted and ignore rest of validation array
问题描述
对于Laravel 4.1项目我有一个小问题,UI我想解决的问题。
For a project with Laravel 4.1 I have a little UI issue I'd like to solve.
一些投入,从AJAX请求对模糊laravel和工作正常。它只是简单地将它的数值。在laravel我再与验证检查。
Some inputs make an ajax call to laravel on blur and that works fine. It simply sends it's value. In laravel I then check with the validator.
public function validate() {
if(Request::ajax()) {
$validation = Validator::make(Input::all(), array(
'email' => 'unique:users|required|email',
'username' => 'required'
));
if($validation->fails()) {
return $validation->messages()->toJson();
}
return "";
}
return "";
}
虽然这个作品中,JSON字符串还包含字段我有没有必要检查。要precise这是反馈我得到:
Although this works, the json string also contains fields I have no need to check. To be precise this is the feedback I get:
{"email":["The email field is required."],"username":["The username field is required."]}
但看到它是在模糊我只想要一个,我居然在返回检查。所以,如果我是模糊的电子邮件,我想要的回报:
But seeing it is on blur I only want the one I'm actually checking in return. So if i'm blurring email I want a return of:
{"email":["The email field is required."]}
现在我知道这是明显的,因为我的数组包含多个字段,但我不喜欢写一个完整的验证每个可能的输入我永远做。
Now I know it's obviously because my array contains multiple fields, but I don't feel like writing a complete validation for each possible input I ever make.
我的问题是:我可以采用某种方式只得到实际公布后值的回报,即使值可能为空,并没有得到数组的靠背
My question is: can I somehow only get a return of the post values that are actually posted, even though the value might be null and not get rest of the array back.
推荐答案
试试这个(未经测试,随意评论/ downvote如果它不工作):
Try this (untested, feel free to comment/downvote if it doesn't work) :
// Required rules, these will always be present in the validation
$required = ["email" => "unique:users|required|email", "username" => "required"];
// Optional rules, these will only be used if the fields they verify aren't empty
$optional = ["other_field" => "other_rules"];
// Gets input data as an array excluding the CSRF token
// You can use Input::all() if there isn't one
$input = Input::except('_token');
// Iterates over the input values
foreach ($input as $key => $value) {
// To make field names case-insensitive
$key = strtolower($key);
// If the field exists in the rules, to avoid
// exceptions if an extra field is added
if (in_array($key, $optional)) {
// Append corresponding validation rule to the main validation rules
$required[$key] = $optional[$key];
}
}
// Finally do your validation using these rules
$validation = Validator::make($input, $required);
添加您需要的字段添加到 $要求
阵列,关键在POST数据作为字段的名称,并在 $可选字段可选的
阵列 - 可选的将只有当该领域在提交的数据存在使用
Add your required fields to the $required
array, the key being the field's name in the POST data, and the optional fields in the $optional
array - the optional ones will only be used if the field exists in the submitted data.
这篇关于Laravel只验证被张贴的项目,而忽略验证阵列的休息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!