Custom validation for plugin settings As a follow-up to this thread, I would like to know how to create custom validation rules for plugin settings, or at least how to return field errors to the plugin settings view. I currently have:

&lt;?php namespace Craft;

class SamplePlugin extends BasePlugin {

    function getName() { ... }
    function getVersion() { ... }
    function getDeveloper() { ... }
    function getDeveloperUrl() { ... }

    public function getSettingsHtml()
    {
        return craft()-&gt;templates-&gt;render('sample/settings', [
            'settings' =&gt; $this-&gt;getSettings()
        ]);
    }

    public function prepSettings($settings)
    {
        // I'm currently doing my 'custom' validation here. But if
        // there's an error, how do I display errors on the settings page?

        return $settings;
    }

    public function rules()
    {
        // Tried this, but since SamplePlugin isn't a Model, it does nothing.
    }

    protected function defineSettings()
    {
        return [
            'mySetting' =&gt; [
                AttributeType::String,
                'required' =&gt; true,
                // Can custom validation rules be set here?
            ]
        ];
    }

}
The solution provided here actually required some adjustments. Here is what ended up working:

In craft/plugins/sample/SamplePlugin.php:

&lt;?php namespace Craft;

class SamplePlugin extends BasePlugin {

    function getName() { ... }
    function getVersion() { ... }
    function getDeveloper() { ... }
    function getDeveloperUrl() { ... }

    public function getSettingsHtml()
    {
        return craft()-&gt;templates-&gt;render('sample/settings', [
            'settings' =&gt; $this-&gt;getSettings()
        ]);
    }

    protected function getSettingsModel()
    {
        return new Sample_SettingsModel();
    }

}


In craft/plugins/sample/models/Sample_SettingsModel.php:

&lt;?php namespace Craft;

class Sample_SettingsModel extends BaseModel {

    protected function defineAttributes()
    {
        return [
            'mySetting' =&gt; [
                AttributeType::String,
                'required' =&gt; true
            ]
        ];
    }

    public function rules()
    {
        $rules = parent::rules();
        $rules[] = ['mySetting', 'validateMySetting'];

        return $rules;
    }

    public function validateMySetting($attribute)
    {
        $value = $this-&gt;$attribute;

        if ( /* validation condition */) {
            $message = Craft::t("Error message");
            $this-&gt;addError($attribute, $message);
        }
    }

}