Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

orest's avatar
Level 13

repetitive validation rules and messages

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 ?

0 likes
3 replies
martinbean's avatar

@orest I don’t really see what the problem is, to be honest.

If I’m looking at validation, I want to be able to read the rules, not see that it uses some abstract “body” rule. A “body” rule tells me nothing about the data under validation, which means I need to look in another location.

orest's avatar
Level 13

the rules required and string are used on several validations and the error message is always the same.

i want to avoid writing the same rule and error message in multiple places

instead i was looking for a solution where the rule and the message are stored in one place ( thus a rule named BodyIsRequired ( but maybe what i'm want to do is "too much" and i can just write the same rule and message since they are quite simple )

I agree that it would be better to read the rules and understand them without reaching another file.

Please or to participate in this conversation.