Home > Blockchain >  Ignore Extra Spaces Mid String Using Laravel Min Validation Rule
Ignore Extra Spaces Mid String Using Laravel Min Validation Rule

Time:12-19

Using the following validation rules:

'somefield' => 'required|min:20',

An input value of "Extra space." will pass min:20 validation.

What is the best way to ignore more than single spaces in the middle of a string when applying the min validation rule so the above input value would fail? Not looking for a client-side solution.

CodePudding user response:

Use method prepareForValidation() in FormRequeet, try:

use Illuminate\Support\Str;

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
$this->merge([
    'somefield' => Str::squish('    laravel    framework    ');
    // laravel framework
    ]);
}

References:

https://laravel.com/docs/9.x/validation#preparing-input-for-validation

https://laravel.com/docs/9.x/helpers#method-str-squish

CodePudding user response:

You can use this simple validation.

'somefield' => ['required','min:20','regex:/^\S*$/u']
  • Related