Laravel only validate items that are posted and ignore rest of validation array

自古美人都是妖i 提交于 2019-12-05 17:44:01

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);

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.

You can also use Laravel requests in a much cleaner way

  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;
  }

I found it. It's going to be something like this:

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 "";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!