从自定义Form Request-Laravel 5.6中获取格式化值



我正在使用自定义表单请求验证所有输入数据以存储用户。

我需要在发送到表单请求之前验证输入,并在我的控制器中获得所有验证的数据。

我有一个regex函数可以验证这个输入,删除不需要的字符、空格、只允许数字等。

希望在控制器中验证所有数据,但仍然没有成功。

Input example: 

$cnpj=29.258.602/0001-25

How i need in controller:

$cnpj=29258602000125

UsuarioController
class UsuarioController extends BaseController
{
public function cadastrarUsuarioExterno(UsuarioStoreFormRequest $request)
{
//Would to get all input validated - no spaces, no!@#$%^&*, etc 
$validated = $request->validated();
dd($data);
}
...
}

UsuarioStoreFormRequest
<?php
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
use IlluminateHttpRequest;
class UsuarioStoreFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'cnpj' => 'required|numeric|digits:14',
];
}

Custom function to validate cnpj
function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
}

您可以在FormRequest中使用prepareForValidation方法。这样,在验证之前,您的输入将在请求中被修改和替换,并且在验证成功后,您通常可以使用$request->get('cnpj');在控制器中检索它。

public function prepareForValidation()
{
$input = $this->all();
if ($this->has('cnpj')) {
$input['cnpj'] = $this->get('cnpj'); // Modify input here
}
$this->replace($input);
}

您可以在UsuarioStoreFormRequest中扩展经过验证的函数,如下所示

/**
* Get the validated data from the request.
*
* @return array
*/
public function validated()
{
$validated = parent::validated();
//Add here more characters to remove or use a regex
$validated['cnpj'] = str_replace(['-', '/', ' ', '.'], '', $validated['cnpj']);
return $validated;
}

这样做:

$string = "29.258.602/0001-25";
preg_match_all('!d+!', $string, $matches);
return (implode("",$matches[0])); 

希望它能帮助

最新更新