craftcms / docs

Documentation for Craft CMS, Craft Commerce, and other official products.
https://craftcms.com/docs
38 stars 144 forks source link

[Content]: "Adding validation rules" - Add code example for entries #570

Closed mandrasch closed 3 months ago

mandrasch commented 5 months ago

Product

Craft CMS

Description

Hi,

just a quick suggestion for the docs:

I tried to find information on how I could add a custom validation rule to a specific field in Entries.

The v3 docs had a specific example for Entry, very helpful

https://craftcms.com/docs/3.x/extend/extending-system-components.html#custom-validation-rules

use craft\elements\Entry;
use craft\events\DefineRulesEvent;
use craft\validators\ArrayValidator;
use yii\base\Event;

Event::on(
    Entry::class,
    Entry::EVENT_DEFINE_RULES,
    function(DefineRulesEvent $event) {
        /** @var Entry $entry */
        $entry = $event->sender;

        // Only worry about entries in the News section
        if ($entry->section->handle !== 'news') {
            return;
        }

        $event->rules[] = ['field:myTagsField', ArrayValidator::class, 'max' => 5, 'on' => Entry::SCENARIO_LIVE];
        $event->rules[] = ['field:myCheckboxesField', ArrayValidator::class, 'max' => 5, 'on' => Entry::SCENARIO_LIVE];
        $event->rules[] = ['field:myTableField', ArrayValidator::class, 'max' => 5, 'on' => Entry::SCENARIO_LIVE];
    }
);

The v4 docs only have a User example and mention custom fields below that

https://craftcms.com/docs/4.x/extend/events.html#adding-validation-rules

Reading this first I totally missed the "You can add validation rules to custom fields in the same handler:" box since I only saw User::EVENT_DEFINE_RULES, in the section before and stopped reading.

A code example for entries could be helpful imho.

Keep up the awesome work with craft! 🚀 👏

AugustMiller commented 3 months ago

Added in 98bdef17fc534fa709b324fc6d8414d5a65d63ff