Throwing error in lifecycle hook doesn't stop script from executing

Lifecycles can’t stop the Creation/Updating of an entry by using the return inside it. The return in lifecycle just means “I don’t want to modify any data before creation/update”.

In that case, you should throw errors instead of returns in beforeCreate/beforeUpdate lifecycles.

So the correct approach to stop a creation will be:

beforeCreate(data, model) {
         if(data.num < 3) {
               throw new Error('Num is not smaller than 3.'); // throwing errors will STOP the creation.
         }
    },

Also, if you are trying to do simple checks, like check the numbers, you can also define its max/min values directly in Content Manager when editing a Number field.
image

The same applies to Text fields, you can define regex patterns to do validation in Admin before creation:
image

1 Like