[Laravel 9, Livewire 2 – upgrading is not currently an option]
I have a Livewire component that validates a number of fields belonging to a User model. The validation rules are stored in the User class and pulled into the component from there.
Usually, when validating User models, I want to validate the username and password fields, but for this particular component, those two fields are not present in the data at all, so they should not be validated. The rules are set up like this:
// User class
public function rules() {
return [
"name" => "required|string",
[other rules…],
"username" => ["sometimes", "required", "email", "unique:App\Models\User,username"],
"password" => ["sometimes", "required", "confirmed", Password::defaults()],
];
}
When I validate the component form, the sometimes rule for the password works as intended: the password field is skipped because it’s not present.
It doesn’t work for the username, though: even though there is no username field in the data, I still get an error message that “The username must be a valid email address”. If I remove the email rule, it works, but then of course it won’t validate whether it’s a valid e-mail address when it is present.
How can I tell the Laravel validator to completely ignore and skip validation if the field is not present in the data, but otherwise validate according to all the rules given?