PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] Laravel sometimes validation rule

 January 22, 2022     laravel, php, validation     No comments   

Issue

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 could this using Laravels validation rules, specifically the 'sometimes' rule. I have this set of rules:

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

This is simplified for the example, there will usually be other rules for other fields and stricter rules for the password. I expect this to only apply the min:8 rule if the password field is present in the passed data, but if I leave the password field empty I get a validation error saying the password field is required.

I'm not sure what I'm not understanding in the docs. Do I need to manually remove the password field before validation if it is the form input was submitted empty like this?

$data = $request->all();

if ('' === $data['password']) {
    unset($data['password'])
}

...and then pass the array into the validator. I think this makes sense but I could do with some confirmation that I'm understanding it correctly. Thanks in advance.


Solution

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

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


Answered By - Nabin Kunwar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing