mahdiaslami's avatar

How prevent duplicating validation rules and its tests?

How prevent duplicating validation rules and its tests?

I have a project with more than 100 API routes. and i problem duplication of validation tests and rules.

assume i have this two routes.

// App\Http\Requests\SignInRequest
// a route for sign in:
// first: POST /api/sign-in
function rules() {
    return [
        'mobile' => 'required|regex:/^(\+989|00989|989|09|9)\d{9}$/'
        ...
    ];
}

// App\Http\Requests\ProfileUpdateReqeust
// route for updating profile:
// second: PUT /api/profile
function rules() { 
    return [
        'mobile' => 'regex:/^(\+989|00989|989|09|9)\d{9}$/',
        'first_name' => 'string|max:255'
        ...
    ]
}

and tests is

// Tests\Requests\SignInRequestTest
mobile is required
mobile can be with country code
mobile can be without country code
mobile should be at least 10 number
...

// Tests\Requests\ProfileUpdateReqeustTest
mobile can be with country code
mobile can be without country code
mobile should be at least 10 number
first name should be string
first name should be shorter than 255 char
...

now, How can i prevent this duplication in our tests and validations.

0 likes
2 replies
Tray2's avatar

I prefer to keep the rules duplicated in these cases but you could move the common ones into the base class and then merge it into the distinct rules.

bugsysha's avatar

I create a Phone class and have a constant or static method return the rule. Then I reference that constant or static method in both places.

Please or to participate in this conversation.