从自定义表单请求中获取格式化值 - Laravel 5.6

Get formatted values from custom Form Request - Laravel 5.6

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

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

我准备了一个正则表达式函数来验证此输入,删除不需要的字符、空格,只允许数字等。

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

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 App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

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

您可以按如下方式扩展 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])); 

希望对你有所帮助

您可以在 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);
}