Skip to content

Latest commit

 

History

History
113 lines (98 loc) · 3.05 KB

Constraints.md

File metadata and controls

113 lines (98 loc) · 3.05 KB

Constraints

The Validator is designed to validate objects against constraints. They are assertions that a condition is true.

Supported constraints

Basic constraints:

String constraints:

Comparison constraints:

Number constraints:

Date constraints:

Choice constraints:

Financial and other Number Constraints:

Other constraints:

Create custom constraint

import { AbstractConstraint } from 'constraint-validator';

export default class MyAwesomeConstraint extends AbstractConstraint {
    /**
     * @return {{message: string}}
     */
    getDefaultOptions() {
        return {
            // provide list of default configuration values
            'message': 'My Awesome constraint failed',
        };
    }

    /**
     * @return {string[]}
     */
    getRequiredOptions() {
        // provide list of required configuration options
        return ['my_option'];
    }

    /**
     * Test provided value and return Error if occurs
     *
     * @param value
     * @param {{}} [options]
     *
     * @return {Error|undefined}
     */
    validate(value, options = {}) {
        // provide your custom validation logic
        let isValid = false;

        /** 
         * hack, hack, hack ...
         * isValid => true || false 
         */

        if (!isValid) {
            // build validation error
            return this
                .getViolationBuilder()
                .setParameter('value', value)
                .build(this.options.message);
        }
    }
}