Skip to content

Custom validations

Alan Berdinelli edited this page Feb 13, 2024 · 6 revisions

If you only need to customize the error message you can use the Message property

You can add custom validations to your schema and they will be executed after all built-in validations in Schemy. Your custom validation method should return true if success, and false if fails.

const Schemy = require('schemy');

// This example validates that name starts with an uppercase letter
const schema = new Schemy({
    name: {
        type: String,
        custom: (value) => /^[A-Z]$/.test(value.substr(0,1))
    }
});

schema.validate({ name: 'alan' }); // => false
schema.getValidationErrors(); // => [ 'Custom validation failed for property name' ]

Custom messages

If you return a string in your validation method, it will fail validation and add your message to the validation output.

const Schemy = require('schemy');

// This example validates that name starts with an uppercase letter
const schema = new Schemy({
    name: {
        type: String,
        custom: function(value) {
            if (!/^[A-Z]$/.test(value.substr(0,1))) {
                return 'Name must start with an uppercase letter';
            }

            return true;
        }
    }
});

schema.validate({ name: 'alan' }); // => false
schema.getValidationErrors(); // => [ 'Name must start with an uppercase letter' ]

Validating against other properties

Schemy will pass other params to your method as well, including the whole body that we are validating and the current schema. This way you can compare against other values of the object.

const schema = new Schemy({
    min: Number,
    max: {
        type: Number, 
        custom: function(value, body, schema) {
            if (value < body.min) {
                return 'Max value must be greater than min value';
            }

            return true;
        }
    }
});

schema.validate({ min: 5, max: 4 }); // => false
schema.getValidationErrors(); // => [ 'Max value must be greater than min value' ]

Clone this wiki locally