Laravel 5 Validation Trim

后端 未结 8 939
梦谈多话
梦谈多话 2020-12-18 05:23

I am a beginner in Laravel 5.

How can I remove whitespaces in validator?? i have read the documentation but there is no validator for trim(remove whitespaces).

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 05:47

    I extended the FormRequest class and overrode the prepareForValidation method which is called before validation happens.

    // anything I don't want trimmed here
    protected $untrimmable = [];
    
    // replace the request with trimmed request here
    protected function prepareForValidation()
    {
        return $this->replace($this->trimData($this->all()));
    }
    
    // recursively trim the fields in the request here
    protected function trimData($data,$keyPrefix = '')
    {
        $trimmedFields = array_map(function($value,$field) use ($keyPrefix){
            // if the value is an array handle it as
            // a request array and send along the prefix
            if(is_array($value)){
                return $this->trimData($value,$this->dotIndex($keyPrefix,$field));
            }
    
            // if the field is not in the specified fields to be
            // left untrimmed
            if(
                !in_array($this->dotIndex($keyPrefix,$field),$this->dontTrim) && 
                !in_array($this->dotIndex($keyPrefix,$field), $this->untrimmable)
            ) {
                return trim((string) $value);
            }
    
            return $value;
    
        }, $data,array_keys($data));
    
        return array_combine(array_keys($data),$trimmedFields);
    }
    

    What it does:

    1. Replace request with a new one with trimmed inputs
    2. Set all fields I don't want trimmed in an untrimmable property.
    3. Handles nested inputs with dot notation .

    Here's a link to the gist https://gist.github.com/msbrime/336a788c7cced2137bdc7896c1241239

提交回复
热议问题