Prohibited Validation Rules in Laravel

Sometimes we wish to forcefully prevent some of the fields in the request.

Now we just got that. Laravel 8 has three validation added for prohibited fields. Let’s walk through a few examples of where the prohibited validation rules might be useful and look at each one in more detail.

Prohibited Validation Rule

The “prohibited” rule checks if the field under validation must be empty or not present or throw an error otherwise.

// PUT /api/licenses/123-456

// {"name":"hello-world", "key":"random-key"}

$validated = $request->validate([
    'name' => 'required|max:255',
    'key' => 'prohibited',
]);
			
// Response: 422

// The key field is prohibited

The above is where a user might expect to update an API key by sending a PUT request to a resource. That field is likely ignored during the request. However, a successful response might lead to the user to believe they were able to update the key when in reality, the API ignored it.

If  prohibited validation rule registers, the key field is present in the request it will terminate the request with 422 HTTP code response code  and throw the error with the message The key field is prohibited.

Prohibited If and Unless Rules

The “prohibited_if ” rule checks if the field under validation must be empty or not present if the another field is equal to any value.

Validator::validate([
‘is_minor’ => true,
‘tos_accepted’ => true
], [
‘tos_accepted’ => ‘prohibited_if:is_minor, true’
]);

The above example is we’re expecting tos_accepted field will be forbidden if is_minor filed accepts true value. This example means someone accepting terms of service that has identified as a minor. Perhaps the application requires a parental registration to consent on their behalf.

The basic idea of “Prohibited_unless” rule is that a given filed should be prohibited from having data unless another field is equal to any value.

Validator::validate([
‘is_deceased’ => false,
‘date_of_death’ => ‘2021-03-09’
], [
‘date_of_death’ => ‘prohibited_unless:is_deceased,true’
]);

The above example might be initially the is_deceased filed set to false value.If we’re expecting the date_of_death field not to be forbidden, the is_deceased’ field set to true value.The example  illustrates perfectly how to use this rule to explicitly prevent contradictory input.

By Ami



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム