Laravel 4:在验证之前修剪输入的最佳实践 [英] Laravel 4 : Best Practice to Trim Input before Validation
问题描述
现在,我会像下面的代码一样分别修剪每个输入:
Now, I do trim for each input separately like below code:
$username = trim(Input::get('username'));
$password = trim(Input::get('password'));
$email = trim(Input::get('email'));
$validator = Validator::make(array('username' => $username,
'password' => $password,
'email' => $email),
array('username' => 'required|min:6',
'password' => 'required|min:6',
'email' => 'email'));
任何一种可以同时进行修整的方法
Is any approach to do Trim at the same time with
Input::all()
或Input::only('username', 'password', 'email')
?
这是什么最佳实践?
推荐答案
注意:如果您的任何输入都是数组(例如"data []" ).
Note: This solution won't work if any of your inputs are arrays (such as "data[]").
您可以尝试执行此操作,在验证之前使用以下一行代码进行修整:
You may try this, trim using this one line of code before validation:
Input::merge(array_map('trim', Input::all()));
现在完成其余的编码
$username = Input::get('username'); // it's trimed
// ...
Validator::make(...);
如果要从修剪中排除某些输入,则如果all()
If you want to exclude some inputs from trimming then you may use following instead if all()
Input::except('password');
或者您可以使用
Input::only(array('username'));
更新:由于新的TrimStrings
中间件,对Laravel 5.4.*
的输入进行了修整.因此,无需担心,因为该中间件在每个请求上都执行,并且还可以处理数组输入.
Update: Since Laravel 5.4.*
inputs are trimmed because of new TrimStrings
middleware. So, no need to worry about it because this middleware executes on every request and it handles array inputs as well.
这篇关于Laravel 4:在验证之前修剪输入的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!