沃梦达 / 编程问答 / php问题 / 正文

Laravel 4:验证前修剪输入的最佳实践

Laravel 4 : Best Practice to Trim Input before Validation(Laravel 4:验证前修剪输入的最佳实践)

本文介绍了Laravel 4:验证前修剪输入的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我分别对每个输入进行修剪,如下代码:

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')?

这样做的最佳做法是什么?

And what is the best practice to do this?

推荐答案

注意: 如果您的任何输入是数组(例如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(...);

如果你想从修剪中排除一些输入,那么你可以使用以下 if 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'));

更新:由于 Laravel 5.4.* 输入因新的 TrimStrings 中间件而被修剪.因此,无需担心,因为此中间件会在每个请求上执行,并且它还处理数组输入.

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.

这篇关于Laravel 4:验证前修剪输入的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 4:验证前修剪输入的最佳实践

基础教程推荐