How do you handle form validation, especially with nested models, in Node.js + Express + Mongoose + Jade

后端 未结 3 675
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 16:04

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 possibly see using

相关标签:
3条回答
  • 2021-02-02 16:47

    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');
      }
    ...
    });
    
    0 讨论(0)
  • 2021-02-02 16:59

    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.

    0 讨论(0)
  • 2021-02-02 17:01

    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.

    0 讨论(0)
提交回复
热议问题