In this guide, we will explore the capibilities of Indicative to validate nested objects and arrays, along with the option to remove unvalidated properties from the data object.
- The terms like
alphaare the pre-defined validation rules. You can also define your own rules for custom needs.
- A field can be validated against multiple rules and Indicative will execute them in sequence from left to right.
- If validation for a field fails, then Indicative will stop the validations chain. However, the
validateAllmethod can be used to prevent this behavior.
Validating nested objects
The aim of Indicative is to keep the schema object simple and readable even when you are validating nested properties. We achieve this using
dot notation to target nested properties inside an object.
The validator will skip nested validations, when top level value is
undefined or not an
object. This is done, so that you can make root level objects optional and only validate their children when they themselves exist.
However, you can enforce the
user object to exist and must be an object using the following rules.
You can validate arrays by defining a specfic index or using the
wildcard (*) to validate all items inside an array.
If you want the
users array to always exists and have a specific length, then make sure to add the following rules.
Removing invalidated fields
Indicative can optionally remove invalidated fields from the data object. Consider the following example:
String based rules
Indicative supports couple of ways to define the validation rules. Let's start with the string based rules and then move to array of function calls.
|Used to separate two or more rules. Example: |
|Used to define arguments for a given rule. Example: |
|Used to define more than one argument for a rule. Example: |
The string based rules are more readable and concise. However, they have handful of downsides too.
- There is no way to know if you have mis-typed a rule, until you run your code and receive a Runtime exception.
- The reserved keywords can conflict with the rules arguments. For example:
colonis a reserved keyword and hence using it as the date format separator will fail.
Array of function calls
The alternative to the string based approach is define rules as an array of function calls.
validations object holds pre-defined validation rules. When using the extend API, Indicative will also add your custom rules to this object.
- Not really. The syntax is more verbose and may span over multiple lines.