Notoriously Pedantic Magistrate

    ajv-error-messages

    2.1.0 • Public • Published

    ajv-error-messages

    Normalise errors from ajv to a simpler format.

    Takes ajv errors and returns a simpler object. Inspired by https://github.com/MauriceButler/jayschema-error-messages

    AJV Version

    v2 of ajv-error-messages has been upgraded to work with v8 of ajv

    Usage

    var normalise = require('ajv-error-messages');
    var SchemaValidator = require('ajv');
    var schemaValidator = SchemaValidator({ allErrors: true });
    
    var schema = {
        description: 'test schema',
        type: 'object',
        additionalProperties: false,
        required: ['foo'],
        properties: {
            foo: {
                type: 'string',
            },
        },
    };
    var invalidData = {
        foo: 2,
    };
    
    var validator = schemaValidator.compile(schema);
    
    function validatingData(data) {
    
        var valid = validator(data);
        var normalisedErrors;
        if (!valid) {
            var ajvErrors = validator.errors
            normalisedErrors = normalise(ajvErrors);
        }
    
        return valid || normalisedErrors;
    }
    
    console.log(JSON.stringify(validatingData(invalidData)));

    results in

    {
        fields: {
            'foo': ['Must be string']
        }
    }
    

    Install

    npm i ajv-error-messages

    DownloadsWeekly Downloads

    141

    Version

    2.1.0

    License

    MIT

    Unpacked Size

    5.43 kB

    Total Files

    5

    Last publish

    Collaborators

    • divinegod