1

I'm trying to validate a password input field, and spaces are not getting caught by the validator. The password field should be a minimum of 6 characters, and the regex should allow spaces within a password, but not at the beginning or end (I've confirmed that this works outside of the validator).

When a user enters in 1+ spaces into the password field (but no other characters) and submits, the validator fails to catch it (i.e., " " isn't caught by the validator).

Here's what my validator looks like:

$this->validate($request, [
    'name' => 'required|max:255|alpha',
    'password' => 'regex:/^[^\s]+(\s+[^\s]+)*$/|min:6|confirmed',
]);
DanielRH
  • 75
  • 1
  • 9

4 Answers4

4

The validator checks if the input isValidatable() by trimming the input, and determining if the input is empty, and despite it's emptiness, if that input should still be validated (i.e., inputs with rules such as required, present, etc are determined to be validatable and are dealt with later on in the validation process).

In this case, since none of these implicit rules were included in the field validation rules, the whitespace input was determined to be not validatable, and never reached the regex or min rules.

HT to jemaclus for digging around and discovering this.

DanielRH
  • 75
  • 1
  • 9
0

You have a mistake in you regex. After the second \s should go * not +. Use the following one:

/^[^\s]+(\s*[^\s]+)*$/

Validator may not work if other rules used together with regex and they are separated with pipelines. So try to use array of rules:

'password' => array('regex:/^[^\s]+(\s*[^\s]+)*$/', 'min:6', 'confirmed')

Andrej
  • 7,474
  • 1
  • 19
  • 21
0

i tested in a test laravel app with this and it seemed to work

'password' => 'required|min:6|confirmed|regex:/^[^\s]+(\s+[^\s]+)*$/',

z1haze
  • 431
  • 4
  • 7
  • If you add required it works (because the validator seems to trim the input, and then the required fails because it's blank), but this is for a password update field on a profile edit page, if they leave it blank, I want it to just not update their password. HT jemaclus -- it seems that the validator simply ignores all whitespace strings... so it's not even reaching the regex or min. – DanielRH Aug 31 '16 at 21:11
0

You can ignore using Regex at all, simply like this

'password'=>[
            'required',
            'min:6',
            function ($attribute, $value, $fail){
                if (strstr($value,' ')) {
                    $fail(__('site.no_whitespaces_allowed_in_password'));
                }
            },
        ],
        'password_confirmation'=>[
            'required',
            'min:6',
            'same:password',
                function ($attribute, $value, $fail){
                if (strstr($value,' ')) {
                    $fail(__('site.no_whitespaces_allowed_in_password_confirmation'));
                }
            },
        ],
Adham shafik
  • 1,044
  • 1
  • 13
  • 16