Skip to content
Advertisement

Whitespace not caught by Laravel validation

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',
]);

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement