Skip to content

Latest commit

 

History

History
119 lines (106 loc) · 3.63 KB

README.md

File metadata and controls

119 lines (106 loc) · 3.63 KB

vlad Build Status

A simple asynchronous JSON validator with a chainable syntax.

npm install vlad

Example

Object Validation

var validate = vlad.promise({
    email: vlad.string,
    location: vlad({
        long: vlad.number.required.within(-180, 180),
        lat: vlad.number.required.within(-90, 90)
    }),

    tags: vlad.array.of(vlad.string.within(3, 10))
});

validate(validObject).then(function(value) {
    /*{
        email: "[email protected]",
        location: {
            long: 70.235,
            lat: 60.234
        },
        tags: ['foo', 'bar']
    }*/
});


validate(invalidObject).catch(function(err) {
    /* GroupValidationError {
        message: "Invalid object.",
        fields: {
            email: FieldValidationError {message: '...'},
            location: GroupValidationError {
                message: 'Invalid object.',
                fields: {
                    long: FieldValidationError {message: '...'}
                }
            },
            tags: ArrayValidationError {
                message: 'Invalid array.',
                fields: [
                    undefined,
                    FieldValidationError {message: '...'},
                    undefined
                ]
            }
        }
    }*/
});

Express Middleware

router.post('/',
    vlad.middleware('body', {
        email: vlad.string.required.pattern(/.*@.*/)
    }),
    function(req, res) {
        res.send(200);
    }
);

router.use(function(err, req, res, next) {
    if (err instanceof vlad.ValidationError) {
        res.status(400).send(err.toJSON());
    } else {
        res.sendStatus(500);
    }
});

Subvalidators

var validate = vlad({
    field: vlad.string.required
});

validate({ field: 'hello world' }).then( /* handle */ );
validate.field('hello world').then( /* handle */ )

API Reference