2

What is the right way to validate incoming data on server side? I'm using lodash for simple validation like isObject or isArray etc, and validator for cases when i need to validate, say, if a string isEmail. But all this looks awkward and i'm not sure if this gonna hurt performance a lot or not so much.

There should be a way to validate incoming data the more elegant way.

1 Answer 1

2

One way to do it would be to use schema-inspector.

It's a module meant to validate json objects based on a json-schema description.

Here is an example from the github README :

var inspector = require('schema-inspector');

// Data that we want to sanitize and validate
var data = {
    firstname: 'sterling  ',
    lastname: '  archer',
    jobs: 'Special agent, cocaine Dealer',
    email: 'NEVER!',
};

// Sanitization Schema
var sanitization = {
    type: 'object',
    properties: {
        firstname: { type: 'string', rules: ['trim', 'title'] },
        lastname: { type: 'string', rules: ['trim', 'title'] },
        jobs: {
            type: 'array',
            splitWith: ',',
            items: { type: 'string', rules: ['trim', 'title'] }
        },
        email: { type: 'string', rules: ['trim', 'lower'] }
    }
};
// Let's update the data
inspector.sanitize(sanitization, data);
/*
data is now:
{
    firstname: 'Sterling',
    lastname: 'Archer',
    jobs: ['Special Agent', 'Cocaine Dealer'],
    email: 'never!'
}
*/

// Validation schema
var validation = {
    type: 'object',
    properties: {
        firstname: { type: 'string', minLength: 1 },
        lastname: { type: 'string', minLength: 1 },
        jobs: {
            type: 'array',
            items: { type: 'string', minLength: 1 }
        },
        email: { type: 'string', pattern: 'email' }
    }
};
var result = inspector.validate(validation, data);
if (!result.valid)
    console.log(result.format());
/*
    Property @.email: must match [email], but is equal to "never!"
*/

The sanitization schema is meant to "clean" your json before validating it (Setting optional values, trying to convert numbers to string, etc).

The validation schema describes the properties your json should respect.

You then call inspector.validate to check if everything is fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.