Skip to main content

Validator

The plugin allows you keep the diagram in a valid state by running a set of callbacks to determine if a command is valid.

To learn more about the plugin, check out the Data validity section.

constructor​

constructor(options: Validator.Options);

The Validator constructor takes the following parameters:

commandManager​

An instance of the CommandManager the validator listens to.

cancelInvalid​

Determine whether to cancel an invalid command or not. If set to false, only the invalid event is triggered.

The default is true.

Methods​

validate()​

validate(actions: string, ...callbacks: Array<Validator.Callback>): Validator;

The method registers callbacks for a given action.

The Validator listens to commands added to the CommandManager and runs the set of callbacks registered for the action.

If the last callback returns an error, the command is canceled (see dia.CommandManager.cancel()). This behavior can be suppressed by setting the cancelInvalid to false.

info

Callbacks are invoked in try catch block. If an error is thrown, it is passed to the next callback in line.

action​

action: string

The action is the name of the event triggered on the graph (see List of triggered events).

validator.validate('add', () => { /* ... */ });

Multiple actions may be given separated by whitespace.

validator.validate('change:source change:target', () => { /* ... */ });

callbacks​

...callbacks: Array<Validator.Callback>

The validation functions.

Any number of validation functions can be passed to the validate() method.

const callback1 = (err, command, next) => { /* ... */ };
const callback2 = (err, command, next) => { /* ... */ };

validator.validate(action, callback1, callback2);

Every callback has the following signature:

  • The err is an error from the previous callback.

  • The command parameter is a command from the CommandManager stack.

  • The next parameter is a function accepting one argument - an error passed to the next callback in line.

    Calling the next() function means going to the next callback. The order of the callbacks is the same as the order they were passed to the validate() method.

    If a call to the next() function is omitted, the validation for the specified action stops.

Events​

The plugin fires the following events:

invalid​

Triggered when an invalid command is detected.

validator.on('invalid', (command: CommandManager.CommandData) => {
console.warn('Invalid command:', command);
});

Types​

The plugin uses the following types:

Callback​

type Callback = (
err: any,
command: CommandManager.CommandData,
next: (err?: any) => void
) => any;

Options​

interface Options {
commandManager: CommandManager;
cancelInvalid?: boolean;
}