After reading this article you will know:
- How to setup validations by using expressions
- How to setup an action that reports validation errors
Learn about expressions here.
Validates by expressions
You can add custom expressions as validation to your data model properties. These expressions can hold custom error messages. These messages will be shown to the end user if the validation fails in the back office and can also be accessed in an after_validation action.
Say you've got a CRM-like application which manages tasks for your user. You might want to validate that the plan_date always is in the future, and let's say it also has to be in the current year. You've got 2 validations which you can implement using 'validates by expressions' as follows:
Expressions to validate a plan date
The message will be added to the form component when triggered. This will result in the following.
This evaluates as 'component label + error message'
You can change the order of the expressions in order to define which expression validation has to be checked first.
Catch validation errors
You can catch validation errors in an after_validation action. This is added especially for imports to trigger an action when a record doesn't validate when created. With this action you can get to know why it didn't validate. In this case the action does a create with skip validations turned on so that the record will be created nevertheless, but then also gets a status 'Validation failed' with the error put in a text property.
Let's walk through the process of using it in an after_validation action.
Validation errors will be available as a hash variable. This hash will look like the following:
"code":"has to be in this year.",
"message":"has to be in this year",
You will have to create a hash variable on your action in which you collect the errors. You can do this using the following expression:
This hash variable will result in the hash as described above.
Next step of your action is checking if you've got any errors.
Create a condition event in your action which checks if there are validation errors on the record using the following expression:
count(var:errors) > 0
You can loop through all errors using a collection of the keys found in the error hash. Use the following expression to get this collection:
Loop through the collection, calling the 'As' field_name. Create another loop inside this loop with a collection using the following expression:
Call the As of the collection field_error_hash. Use the following expression to fetch the code from the error in a following event:
The code above is the set error message in the validation rule. You could save this to the record directly or create another model and link it with a relation. This will allow you to see which validation errors occurred when and on which records.