ardent
ardent copied to clipboard
Only validate changed fields
Say I have a user model like this:
class User {
public static $rules = [
'email' => 'sometimes|required|unique:users,email|email',
'firstname' => 'sometimes|required|min:1',
'lastname' => 'sometimes|required|min:1',
];
}
The user is already saved in database, but without e-mail, firstname, or lastname.
The user wish to update ONLY his e-mail. When he sends the request, only containing an e-mail field, the validation will fail, because he did not provide an firstname and lastname.
How can I avoid that? I.e. only validate the fields that are sent in the request; so if firstname is not sent, Ardent will not validate it, and instead only validate the fields that are present.
My current, very hacky, workaround
/**
* Only validate the changed fields
* @return [type] [description]
*/
public function validateChangedFields() {
$rules = [];
foreach($this->getDirty() as $attribute => $value){
$original= $this->getOriginal($attribute);
//echo "Changed $attribute from '$original' to '$value'<br/>\r\n";
$rules[$attribute] = static::$rules[$attribute];
}
return $this->validate($rules);
}
It might explain better what I am trying to achieve.