Home > database >  validate white space at the beginning and end of string with regex
validate white space at the beginning and end of string with regex

Time:09-04

someone who can help me with a regular expression to be able to validate the blank spaces at the beginning and end of a string, currently I manage this but it does not work for me.

try {
    DB::beginTransaction();

    $validatedData = $request->validateWithBag('marcas', [
        'marca'       => ['required', 'regex:/^\s |[a-zA-Z\t\h] |(^$) |\s $/'],
        'descripcion' => ['required'],
    ]);

    $show = Marca::create($validatedData);

    DB::commit();

    $success =  toast('Marca agregada con exito!', 'success', 'top-right');
} catch (\Exception $e) {
    DB::rollBack();

    toast('Datos requeridos o invalidos!','error','top-right');        
}
   
return redirect()->route('marcas.index', with('success'));

Example:

valid data:no space

invalid data: space at the beginning

this is so that when my user fills an input and adds a space either at the beginning or end of the text to be saved, the regex detects it

CodePudding user response:

Input Trimming & Normalization

By default, Laravel includes the App\Http\Middleware\TrimStrings and App\Http\Middleware\ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the global middleware stack by the App\Http\Kernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

  • Related