JavaScript validators

A Javascript Valiator is a great way to enable you to apply custom rules and logic to actions in JRNI without having to replace large sections of the platform

The two common use cases are for ensure an action is allowed, or to provide validation to a form.

You can register a validator with the command:

Configurator.registerValidator(validator_name, {
    name: a unique name,
    message: an error message to be shown if this validator fails,
    debounce: number of millisecond until it runs this validator again,
    validation_function: the function to call
});

This function allows you to create a named validation function that is called with specific data to validate an action is happening. A list of validators, and their data is listed below.
The function is expected to resolved to a promise that either resolves, sucessfully if valid, or is rejected if invalid. You can can support a default message that may be shown in the UI in the event of failure. You should also supply a debounce value that is used to ensure the function is not called to quickly in a fast updating screen.

An example of a default validator is a client form email validator, that is used to check a new client does not match an existing one by checking their email.

async function duplicateEmail(modelValue, viewValue) { 
    if (modelValue) { 
        const company = bbAuthorisation.getCompany();   
        return company.$get('client_by_email', {email: modelValue});
    } else { 
        return Promise.resolve(); 
    } 
}

Configurator.registerValidator('Studio.Form.new_client.email', {
    name: 'duplicateEmail',
    message: 'A customer already exists with that email address',
    debounce: 500,
    validation_function: duplicateEmail
});

The name parameter is unique for each validator type, and allow you to override a default validator, or unregister an existing one. You can unregister a validator by calling:

Configurator.unregisterValidator(validator_name, unique_name);

for example

Configurator.unregisterValidator('Studio.Form.new_client.email', 'duplicateEmail');