1

I have a custom text field in a module that the user populate with an EAN number. The input is getting validate by a "match" validator and then is serialized before save to get ride of the various variants of the EAN the user can enter ("978-2-87929-647-0", "978.2.87929.647.0" and so on…). But now I need to validate is uniqueness and I can't find the right way to do this.

How can I normalize the input and then test if this normalized value already exists in the DB?

I cannot find a way to get the actual user input and normalize it before validate it.

I guess I have to use the "UniqueValidator" to test if the entry already exists in the DB.

Thanks for your help.

1

If your model somehow extends Yii's Model (which I think it does because you use Yii validators), you can use the beforeValidate() method to change attribute values before validation:

public function beforeValidate()
{
    // Before validation, normalize the attribute's value with whatever method you create for it
    $this->attribute = $this->yourNormalizationMethod($this->attribute);
}

After that, you can use Yii's UniqueValidator to make sure the attribute's value is unique. The docs show you some of it's possible configs, I'm sure you can make it work!

1
  • Thanks for your anwser. Unfortunately, the "beforeValidate()" method does not seems to fire up. public function beforeValidate() { return false; } does not raise anything in the Craft CP. Where should I declare this function? Do you have any example of this method working in a Field class? – scandella May 6 '20 at 15:14

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.