Reputation: 75
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',
]);
Upvotes: 1
Views: 3892
Reputation: 1044
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'));
}
},
],
Upvotes: 0
Reputation: 75
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.
Upvotes: 4
Reputation: 440
i tested in a test laravel app with this and it seemed to work
'password' => 'required|min:6|confirmed|regex:/^[^\s]+(\s+[^\s]+)*$/',
Upvotes: 0
Reputation: 7504
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'
)
Upvotes: 0