How do you handle form validation, especially with nested models, in Node.js + Express + Mongoose + Jade
How are you handling form validation with Express and Mongoose? Are you using custom methods, some plugin, or the default errors array?
While I could possibl开发者_StackOverflow社区y see using the default errors array for some very simple validation, that approach seems to blow up in the scenario of having nested models.
I personally use node-validator for checking if all the input fields from the user is correct before even presenting it to Mongoose.
Node-validator is also nice for creating a list of all errors that then can be presented to the user.
Mongoose has validation middleware. You can define validation functions for schema items individually. Nested items can be validated too. Furthermore you can define asyn validations. For more information check out the mongoose page.
var mongoose = require('mongoose'),
schema = mongoose.Schema,
accountSchema = new schema({
accountID: { type: Number, validate: [
function(v){
return (v !== null);
}, 'accountID must be entered!'
]}
}),
personSchema = new schema({
name: { type: String, validate: [
function(v){
return v.length < 20;
}, 'name must be max 20 characters!']
},
age: Number,
account: [accountSchema]
}),
connection = mongoose.createConnection('mongodb://127.0.0.1/test');
personModel = connection.model('person', personSchema),
accountModel = connection.model('account', accountSchema);
...
var person = new personModel({
name: req.body.person.name,
age: req.body.person.age,
account: new accountModel({ accountID: req.body.person.account })
});
person.save(function(err){
if(err) {
console.log(err);
req.flash('error', err);
res.render('view');
}
...
});
I personaly use express-form middleware to do validation; it also has filter capabilities. It's based on node-validator but has additional bonuses for express. It adds a property to the request object indicating if it's valid and returns an array of errors.
I would use this if you're using express.
精彩评论