I'm trying to come up with a solution to avoid writing the same validation rules and messages over and over.
For example i have the following rules for the body attribute
public function rules()
{
return [
'body' => ['string','required'],
];
}
I want the validation message for both rules to be the same.
One approach is to create two custom rules and, string and required and write the message that i want in each rule.
class BodyMustBeString implements Rule
{
public function passes($attribute, $value)
{
if (is_string($value)) {
return true;
}
return false;
}
public function message()
{
return 'Please enter a valid message.';
}
}
class BodyIsRequired implements Rule
{
public function passes($attribute, $value)
{
if (empty($value)) {
return false;
}
return true;
}
public function message()
{
return 'Please enter a valid message.';
}
}
The other approach is to create one custom rule for the body attribute attribute that consists of both string and required rules.
class BodyRules implements Rule
{
public function passes($attribute, $value)
{
if ( !empty($value) && is_string($value)) {
return true;
}
return false;
}
public function message()
{
return 'Please enter a valid message.';
}
}
Do you have any other approach or do you agree with any of my approaches ?