Laravel sometimes validation rule

后端 未结 7 2203
孤街浪徒
孤街浪徒 2021-02-08 07:38

I am trying to validate a password field only if it is present. I want to allow someone to edit a user and they may or may not want to change the users password. So I thought I

相关标签:
7条回答
  • 2021-02-08 08:16

    I think we should tell laravel If password is not empty put the rules otherwise do nothing.

    $this->validate($request, [
      'password' => $request->password != null ?'sometimes|required|min:8': ''
    ]);
    
    0 讨论(0)
  • 2021-02-08 08:16

    In edit mode you fill password field by for example "********" and in update mode validate like this

    $this->validate($request, [
        'password' => 'required|min:8',
    ]);
    

    and in controller check $data['password']='********' find old password and

    $data['password']='old password in db'
    

    and $data['password']!='********' update pssword

    0 讨论(0)
  • 2021-02-08 08:17

    Docs don't make it clear, But removing required makes it work.

    $this->validate($request, [
        'password' => 'sometimes|min:8',
    ]);
    
    0 讨论(0)
  • 2021-02-08 08:24

    As an option to the selected answer, you can use:

        $this->validate($request, [
           'password' => 'nullable|min:8',
        ]);
    
    0 讨论(0)
  • 2021-02-08 08:26

    Laravel sometimes validation rule and their function:

    accepted The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

    active_url The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.

    after:date The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function: 'start_date' => 'required|date|after:tomorrow' Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date: 'finish_date' => 'required|date|after:start_date'

    after_or_equal:date The field under validation must be a value after or equal to the given date. For more information, see the after rule.

    alpha The field under validation must be entirely alphabetic characters.

    0 讨论(0)
  • 2021-02-08 08:34

    "I am trying to validate a password field only if it is present."

    To do this, you can use the "nullable" rule within the validation system.

    For example:

    $this->validate($request, [
        'password' => 'sometimes|nullable|min:8',
    ]);
    

    For more information take a look at https://laravel.com/docs/5.6/validation section under "A Note On Optional Fields"

    0 讨论(0)
提交回复
热议问题