简体   繁体   中英

how to implement regex in laravel validator

I'm making an employee management API through Laravel in PHP. First of all, sorry if this question has already been asked in the forum but I have not been able to find exactly the answer I needed. The thing is that I want to validate the password through a RegEx inside the Validator. I don't know if this is the right way to do it, if so I would appreciate if someone could tell me the right way to validate the password. Thank you.

$validator = Validator::make(json_decode($req->getContent(), true), [
        'name' => 'required',
        'puesto' => 'required',
        'password' => 'required|regex:/(?=.*[a-z])(?=*[A-Z])(?=.*[0-9])(?=.*[A-Za-z0-9]).{6,}/',
        'email' => 'required|unique:users',
        'salario' => 'required',
        'biografia' => 'required',
    ]);

Follow

'password' => 'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'

You can the add the length as your need

For more: https://laravel.com/docs/6.x/validation#rule-regex

You can also use a custom validation rule

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrongPassword implements Rule
{
    public function passes($attribute, $value)
    {
        return preg_match(
            "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/",
            $value
        );
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The password does not satisfy strong password policy.';
    }
}

Use epx:

'password' => ['min:8', new StrongPassword]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM