对于使用Laravel 4.1的项目,我有一个我想解决的UI问题。
有些输入会对模糊的laravel进行ajax调用,并且工作正常。它只是发送它的价值。在laravel我然后检查验证器。
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字符串还包含我无需检查的字段。确切地说,这是我得到的反馈:
{"email":["The email field is required."],"username":["The username field is required."]}
但看到它处于模糊状态我只想要一个我实际检查的那个。因此,如果我模糊电子邮件,我想要返回:
{"email":["The email field is required."]}
现在我知道它显然是因为我的数组包含多个字段,但我不想为我曾经做过的每个可能的输入写一个完整的验证。
我的问题是:我能以某种方式只获得实际发布的post值的返回值,即使该值可能为null并且没有得到其余的数组。
答案 0 :(得分:2)
试试这个(未经测试,如果不起作用,请随时评论/ downvote):
// 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);
将所需字段添加到$required
数组中,键是POST数据中字段的名称,以及$optional
数组中的可选字段 - 只有在字段中才会使用可选字段存在于提交的数据中。
答案 1 :(得分:2)
您还可以更清洁地使用Laravel请求
public function rules(){
$validation = [];
$input = Request::all();
if (array_key_exists('email', $input)) {
$validation['email'] = 'unique:users|required|email';
}
if (array_key_exists('username', $input)) {
$validation['username'] = 'required|min:6';
}
return $validation;
}
答案 2 :(得分:1)
我找到了。它会是这样的:
if(Request::ajax()) {
$arr = array();
$arr['email'] = 'unique:users|required|email';
$arr['username'] = 'required|min:6';
$checks = array();
foreach($arr as $key => $value) {
if(Input::has($key)) {
$checks[$key] = $value;
}
}
if(count($checks)) {
$validation = Validator::make(Input::all(), $checks);
if($validation->fails()) {
return $validation->messages()->toJson();
}
}
return "ok";
}
return "";