0

Using this fantastic article on validation, I have written a custom validator class. Everything is working, but I'm curious about the rules and defineAttributes method(s). Most likely I'm just misunderstanding how it all works.

MyModel.php

    public function defineAttributes()
    {
        return array(
            'firstName' => array(
                'type' => AttributeType::Name,
                'required' => true
            ),
            'lastName' => array(
                'type' => AttributeType::Name,
                'required' => true
            ),
            'email' => array(
                'type' => AttributeType::Email,
                'required' => true
            ),
            'phone' => array(
                'type' => AttributeType::ClassName,
                'maxLength' => 14
            )
        );
    }

    public function rules()
    {
        $rules = parent::rules();

        $rules[] = ['email', 'Craft\MyPlugin_EmailValidator'];

        return $rules;
    }

Do I really need both? I (thought) that defineAttributes was the rules method. Everything is working properly; I'm doing a check to make sure the email is unique. I have a unique key defined on the record as well.

Thank you!

1 Answer 1

0

You need both because there is no way to define custom validation rules from defineAttributes().

Ultimately things like 'maxLength' => 14 in defineAttributes() automagically get normalized down to the $rules array that gets returned from the rules method, so you're just appending your custom rule onto that when you call:

$rules = parent::rules();
$rules[] = ['email', 'Craft\MyPlugin_EmailValidator'];
1
  • That makes perfect sense, I was more curious if I was re-inventing the wheel by including the rules call in addition to the defineAttributes method. Thank you!
    – Damon
    Commented Apr 22, 2015 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.