gcanti / tcomb-validation

Validation library based on type combinators
MIT License
400 stars 23 forks source link

http post validation #65

Closed iyezhou closed 7 years ago

iyezhou commented 7 years ago

hi, when I use restify create an API, and use validation like:

var check = t.struct({
    username: t.String,
    realname: t.String,
    password: t.String,
    age: t.Number,
    active: t.Boolean
});

module.exports = {
    name : 'User',
    check: check
};
function create(req, res, next) {
    var result = t.validate(req.body, validate.User.check);
    var values = new validate.User.check(req.body);

    if (!result.isValid()) {
        res.send(422, result.errors);
    }
}

when I send a post request with params "age=20", then throw an Exception, cannot cat age param type to number

throw new TypeError('[tcomb] ' + message);
  ^

TypeError: [tcomb] Invalid value "20" supplied to Struct{username: String, realname: String, password: String, age: Number, active: Boolean}/age: Number
gcanti commented 7 years ago

You must ensure that req.body is valid otherwise User.check will throw

function create(req, res, next) {
    var result = t.validate(req.body, validate.User.check);

    if (!result.isValid()) {
        res.send(422, result.errors);
    } else {
        var values = result.value // <= instance of validate.User.check
    }
}
iyezhou commented 7 years ago

@gcanti Also can't pass validation, throws code 422

[
    {
        "message": "Invalid value \"30\" supplied to /age: Number",
        "actual": "30",
        "path": [
            "age"
        ]
    },
    {
        "message": "Invalid value \"1\" supplied to /active: Boolean",
        "actual": "1",
        "path": [
            "active"
        ]
    }
]
function create(req, res, next) {
    var result = t.validate(req.body, validate.User.check);

    if (!result.isValid()) {
        res.send(422, result.errors);
    } else {
        //var values = new validate.User.check(req.body);
        var values = result.value;
        //var values = new validate.User.check(result.value);
        console.log(values);

        return User.create(values)
            .then(function (entity) {
                res.send(entity);
            })
            .catch(function (err) {
                return next(new errors.InternalError(err.message));
            });
    }
}
iyezhou commented 7 years ago

how to convert a http param(String) to a Number value