Home > Software design >  laravel validation rule to remove whitespaces
laravel validation rule to remove whitespaces

Time:11-16

I want to validate a phone number. For example, one shouldn't able to store a number like the following: '07911 123456', '079 11123456', '0791112 345 6'.

What I've tried:

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

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. White spaces may allow but, the number which is not allowed shouldn't allow. No matter how many white spaces 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