Skip to content

Instantly share code, notes, and snippets.

@khanghoang
Created December 4, 2014 16:16
Show Gist options
  • Save khanghoang/b42ec0749f5dc0b0fc67 to your computer and use it in GitHub Desktop.
Save khanghoang/b42ec0749f5dc0b0fc67 to your computer and use it in GitHub Desktop.
Sails request validation
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)?
@hussainb
Copy link

hussainb commented Apr 5, 2015

I know I am late for this but since this comes up in search results, I will add what I did when I needed to do the same

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment