Home > Software design >  Laravel validation with min character length and 1 numeric number
Laravel validation with min character length and 1 numeric number

Time:02-15

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

CodePudding user response:

You can try digits_between like below ->

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

CodePudding user response:

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

CodePudding user response:

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()
    ]
]);

CodePudding user response:

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,}/']

CodePudding user response:

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]*$/']);
  • Related