Specs
Specs

Reputation: 31

Validate request parameters in SailsJS

In SailsJS, I would like to validate request parameters using the same mechanism as when models are validated when model actions are performed.

So when you define a model you use the "attributes" option to specify your parameter properties, and they are then used for validation.

But what if you'd like to validate say a login form or email form on the server side, thus there is no model needed for it and you'd just like to validate the parameters?

So I'd like to be able to do something like this:

//login validation
req.validate({
   email: { required: true, email: true },
   password: { required: true }
});

//send email validation
req.validate({
   subject: { required: true, type: 'string' },
   to: { required: true, type: 'string' },
   body: { required: true, type: 'string' }
});

A function req.validate is mixed in for all requests and called if req.options.usage is set for the request, I've played with that a bit but I don't quite understand what it's doing. There is no documentation on this nor in "anchor" which is what's used for the validation.

Any help or suggestions on how I could achieve this (preferably with some undocumented SailsJS feature)?

Upvotes: 3

Views: 4159

Answers (2)

hussainb
hussainb

Reputation: 1296

As per sailsjs docs Model Validations.

Notes This is shorthand for Model.validate({ attributes }, cb) If you .save() without first validating, Waterline tries to convert. If it can't, it will throw an error. In this case, it would have converted the array to the string 'Marie,Hank' There will be no parameters in the callback unless there is an error. No news is good news. This is an instance method. Currently, instance methods ARE NOT TRANSACTIONAL. Because of this, it is recommended that you use the equivalent model method instead.

yourLoginModel.validate(req.body, function(err) {
    console.log(JSON.stringify(err));
});

Upvotes: 1

josebaseba
josebaseba

Reputation: 101

Sails req.validate() is used in the core of Sails and if you want to use it in the controllers you have to work with the try catch:

try{
    req.validate({
        email: { type: 'string' },
        password: { type: 'string' }
     });
}catch(err){
     return res.send(400, err);
}

Or it can set a req.flash error too... Check this file for more details:

https://github.com/balderdashy/sails/blob/045fc6630fd915dce1abd89844e4164a9276a8cd/lib/hooks/request/validate.js

I'm woking in my own implementation of this method, with the new feature of installing hooks with npm in v0.11, migration guide:

https://github.com/Josebaseba/sails-hook-validator

It still under development but I think that it will be ready when sails 0.11 arrives.

Upvotes: 1

Related Questions