rev77
rev77

Reputation: 21

Laravel validation with min character length and 1 numeric number

I want to validate my password input to contain at least ten characters and only 1 number. But when I tried this in my controller, it didn't work. So how can I do it?

$request->validate(['password' => 'required|min:10|numeric|max:9']);

Upvotes: 2

Views: 9600

Answers (5)

Vishal Chavda
Vishal Chavda

Reputation: 11

This regex will validate your password must contain only one numeric number and min attribute validate minimum length of the password.

$request->validate(['password'=>'required|min:10|regex:/^[^\d\n]*\d[^\d\n]*$/']);

Upvotes: 1

Kongulov
Kongulov

Reputation: 1161

This regex will give you the strongest password. Password must contain at least one uppercase letter, lowercase letter and at least 1 number

'password' => ['required', 'string', 'min:10', 'regex:/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{10,}/']

Upvotes: 0

user633440
user633440

Reputation:

Use the Password rule object that requires at least one number.

Password::min(10)->numbers();

This is the validation you are looking for.

$request->validate([
    'password' => [
        'required',
        'string',
        Password::min(10)
            ->numbers()
    ]
]);

Upvotes: 0

apokryfos
apokryfos

Reputation: 40673

You can do a combination of regex and min validation:

$request->validate([
      'password' => [ 'required', 'min:10', 'regex:/^[a-z]*\d[a-z]*$/i' ];
]);

This requires a min length of 10 and exactly 1 number. If you allow other characters you can put them in the [a-z] groups

Upvotes: 0

Md. Golam Rabbani
Md. Golam Rabbani

Reputation: 104

You can try digits_between like below ->

$request->validate(['password' => 'required|min:10|digits_between:2,5]);

Upvotes: 0

Related Questions