Tom Pennetta
Tom Pennetta

Reputation: 512

NodeJS MVC Model Validation

This may be a general-ish question but I was wondering if anyone has a recommendation for implementing Model validation for a NodeJS MVC application. I am currently developing an application in which Models have required and optional fields when storing in persistent data (DynamoDB).

I was thinking of just having a validation function inside the model file which ensures the appropriate fields are formatted and populated as necessary, but want to make sure the approach is modular, reusable, clean, and efficient.

There are examples out there for utilizing this kind of function in .Net MVC framework, but not really a custom implementation, in particular with Javascript.

Example Model:

User

var User = function (userObj) {
  this.email = userObj.email;         //required
  this.firstName = userObj.firstName; //required
  this.company = userObj.company;     //optional
}

Any feedback is appreciated!

Upvotes: 0

Views: 2354

Answers (1)

Travis Kaufman
Travis Kaufman

Reputation: 2937

I highly, highly recommend joi

var joi = require('joi');
var userSchema = joi.object().keys({
  email: joi.string().email().required(),
  firstName: joi.string().required(),
  company: joi.string() // or object, or what have you
});

var User = function(userObj) {
  var err = userSchema.validate(userObj).error;
  if (err) {
     // handle error and abort
  }
  // other code...
}

Alternatively you could create a custom validate function on the model's prototype that wraps joi's validation.

The README has a ton of documentation, and it's super easy to use, and outputs all the information you'd ever need for a rest api (in fact you can plug it directly into hapijs)

Upvotes: 2

Related Questions