Magento – Magento 2 model fields validation

magento2modelvalidation

Where is the correct place to validate field in model?

For example, I have a database, with a table Product, but the database designer didn't force NOT NULL in some required fields (for instance, column SKU). So now I have to check whether these fields are NULL or not by code

I thought it will be added in setData() method. But I think setData() should only care about the "set data" job. Is there any better place for this validation job?

Best Answer

As far as I know, our model usually derives from \Magento\Framework\Model\AbstractModel class. So, we can validate the data before saving it by using Observer or overload beforeSave method in our Model.

Related Topic