2

I've been looking at http://straightupcraft.com/articles/the-definitive-guide-to-validation-in-craft which seems to concentrate on custom models. However I am looking to validate data posted to a plugin that stores that data as core EntryModels.

So let's say you create a Section and assign some Fields in its field layout. You can set each Field to be required but I want to do more than that and check if it's an integer or if it's unique.

I am currently doing that in my service class:

private function validateReference()
{
    $reference = craft()->request->getPost('reference');

    $existingEntryCount = craft()->elements->getCriteria(ElementType::Entry)->total(array(
        'reference' => $reference
    ));

    return ($existingEntryCount === 0);
}

That all works but I am wondering if instead I should be setting the validation properties of each Field in this service and then just running a core validate method?

1

Your best bet is going to be to write your own field type for this. You can extend one of the built-in field types if you want.

You would put your custom validation logic in your field type’s validate() method.

  • 1
    Thanks, Brandon. We're using text, textarea and select fields, so we'd have to create 3 custom field types just to add some basic validation in. Is there no simpler way other than validating directly in the service? – Russ Back Nov 11 '14 at 19:42
  • I ended up creating a simple text field that validates uniqueness across the relevant ElementType: github.com/fuel-digital/Craft-Unique-Text-FieldType – Russ Back Nov 26 '14 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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