Model validation hooks are a powerful feature of Builder that help you define custom validation logic for your model's content using JavaScript.
To set up a model validation hook:
- Go to Models.
- Open the model you want to validate and click the Show More Options button.
- Click the Edit Validation Hook button.
- In the code editor that opens, add your validation logic.
The following video shows this process:
When you click Edit Validation Hook, a code editor opens where you can add your validation hook. The placeholder code serves as an example:
async function run() {
if (contentModel.data.get('myProperty') === 'some invalid value') {
return {
level: 'error',
message: 'myProperty is invalid!'
}
}
}
return run();
The code you write here needs access to these constants:
model
: The model object being validated. This contains information about the structure and settings of the model.contentModel
: The entire content object currently loaded in the Visual Editor. This includes all the data and variations associated with the content.editingVariation
: The current content variation being edited. This gives access to the specific variation of the content being validated.
These constants help you access and manipulate the data within the content being validated. For example, you can retrieve values of specific properties, check conditions, and perform custom checks based on the content's attributes.
Validation works by returning validation error objects from this code or returning nothing (undefined
) to indicate no errors.
When validation errors occur, you need to return a JavaScript object representing each error. This object must have specific properties that provide information about the nature and severity of the error.
The validation error object are regular JavaScript objects and should have the following shape:
level
: (required) Indicates the severity of the problem. Possible values are the stringswarning
orerror
, depending on the seriousness of the issue found during validation.message
: (required) Main error text, which describes the problem that occurred during validation.secondaryMessage
: (optional) An additional text that can provide more context or details about the error.element
: (optional) If the validation error is specific to a particular element in the content, you can specify that element here. This is useful when you want the Visual Editor to highlight the element in question for the user's convenience.moreInfoUrl
: (optional) A URL for external help on the error.affectedElements
: (optional) In cases where the error affects multiple elements in the content, you can specify all the affected elements as an array.
You can return a single object to indicate a single error, or you can return an array of these errors to indicate more than one.