# Magento 2 model fields validation?

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?

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.

Model is used to interact with data Resource model is used to interact with database (CRUD for example)

So I think the best place to check data validation is in Resource model.

In Resource model, there is a method called _beforeSave

    /**
* Process post data before saving
*
* @param \Magento\Framework\Model\AbstractModel $object * @return$this
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _beforeSave(\Magento\Framework\Model\AbstractModel \$object)
{
}


Override this function to validate data.