Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

php - 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() or Input::only('username', 'password', 'email')?

And what is the best practice to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Now do the rest of your coding

$username = Input::get('username'); // it's trimed 
// ...
Validator::make(...);

If you want to exclude some inputs from trimming then you may use following instead if all()

Input::except('password');

Or you may use

Input::only(array('username'));

Update: Since Laravel 5.4.* inputs are trimmed because of new TrimStringsmiddleware. So, no need to worry about it because this middleware executes on every request and it handles array inputs as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...