我是Laravel 5的初學者。Laravel 5 Validation Trim
如何刪除驗證器中的空格?我已閱讀文檔,但沒有驗證修剪(刪除空格)。
這裏我的規則
$rules = [
'name' =>'required',
'email' => 'required|email',
'address' => 'required',
'phones' => 'required'
];
謝謝您的回答。
我是Laravel 5的初學者。Laravel 5 Validation Trim
如何刪除驗證器中的空格?我已閱讀文檔,但沒有驗證修剪(刪除空格)。
這裏我的規則
$rules = [
'name' =>'required',
'email' => 'required|email',
'address' => 'required',
'phones' => 'required'
];
謝謝您的回答。
驗證器不能更改任何輸入數據。修剪驗證器存在於CodeIgniter中,但對於我來說這是不適合執行修剪的地方。
,可以自動通過使用修剪所有輸入這樣的:
Input::merge(array_map('trim', Input::all()));
現在做你的代碼的其餘部分:
$username = Input::get('username'); // it's trimed
// ...
Validator::make(...);
您可以使用下面的代碼來修整所有的字符串輸入(如你可能在輸入中有陣列)
// trim all input
Input::merge(array_map(function ($value) {
if (is_string($value)) {
return trim($value);
} else {
return $value;
}
}, Input::all()));
public function formatInput()
{
$input = array_map('trim', $this->all());
$this->replace($input);
return $this->all();
}
在Laravel 5.2或5.3,您可以使用裝飾的空格去掉這樣
$input = array_map('trim', $request->all());
所以這將刪除所有發佈和空間形式輸入驗證將正常工作
我延長了FormRequest
類覆蓋在驗證發生之前調用的prepareForValidation
方法。
// 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);
}
做些什麼:
untrimmable
物業修剪各個領域。這裏有一個鏈接到要點https://gist.github.com/msbrime/336a788c7cced2137bdc7896c1241239
$data = $r->all();
foreach ($data as $key => $value) {
if($value!=""){ //If your primaryKey id is autoincrement
$data[$key] = preg_replace('/\s{2,}/',' ',$value);
}
}
$variable = new modelName($data);
$variable->save();
//Here Parameter Explaination
=> '/\s{2,}/' Pattern must write between '/ /' and \s{2,} means 2 or more than 2 spaces sholud be trim
=> ' ' second parameter is with. Means 1st parameter replace with 2nd parameter(here, one space)
=> $value is variable which is trim
確定..我我會嘗試這..感謝了很多.. – 2015-04-01 09:08:26
這不支持數組。 @Alex答案更好。 – kjdion84 2017-06-04 19:50:11