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).
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:
untrimmable property.Here's a link to the gist https://gist.github.com/msbrime/336a788c7cced2137bdc7896c1241239