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:验证前修剪输入的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)