Home > Net >  laravel valitation rule to remove whitespaces
laravel valitation rule to remove whitespaces

Time:11-15

I don't want you to be able to save a certain phone number regardless of whether you write it with whitespaces or not. The number is entered in an input field and transmitted to the database via a send button. Is there a validation rule for this or another possibility?

'number' => ['required', 'number', Rule::notIn('07911123456')],

For example, you shouldn't be able to enter either: '07911 123456', '079 11123456', '0791112 345 6'

I've already tried the regex rule(https://laravel.com/docs/6.x/validation#rule-regex), but it doesn't do exactly what I want. I want to allow whitespaces but the number that is not allowed should still not be allowed no matter how many whitespaces are included.

CodePudding user response:

Before You post it to server You could remove whites-spaces:

number = '07911 123456';
number = number.replace(/\s/g, '');
var intNumber = parse.Int(number);

For php part You could use:

$number = preg_replace('/\s /', '', $number);

CodePudding user response:

you can trim the name input before validating it ....

in you request:

 public function rules()
    {
      $this->merge(['number'=>str_replace(' ', '',$this->input('number'))]);

       return [
        'number' => ['required', 'number', Rule::notIn(['07911123456'])],
        ];
}

CodePudding user response:

Try this solution

if number filed is not array

<?php 

$validator = [   
    'number' => [
        'required',
        'regex:/^[0-9][0-9\s] [0-9]$/',  // check number with white space
        function ($attribute, $value, $fail) {
            if ('07911123456' === \preg_replace('/\s /', '', $value)) {
                $fail('Message fail');

                return false;
            }

            return true;
        }, 
    ],
// ... another rules
];

$validator = Validator::make($request->all(), $validator);

If number field is array

<?php


$validator = [
    'number' => [
        'required', 'array',
     ],
     'number.*' => [
        'regex:/^[0-9][0-9\s] [0-9]$/',  // check number with white space
        function ($attribute, $value, $fail) {
            if ('07911123456' === \preg_replace('/\s /', '', $value)) {
                $fail('Message fail');

                return false;
            }

            return true;
        },
     ],
// ... another rules
];

$validator = Validator::make($request->all(), $validator);

Tested:

https://regexr.com/69hh6

Docs:

https://laravel.com/docs/8.x/validation#rule-regex

https://laravel.com/docs/8.x/validation#using-closures

https://laravel.com/docs/8.x/validation#validating-nested-array-input

https://www.php.net/manual/en/function.preg-replace.php

  • Related