Himanshu Joshi
Himanshu Joshi

Reputation: 73

Validation in MEAN stack .....?

I am developing a MEAN stack application but i stuck at validation(user-inputs). I know the client-side validations are done in Angular-JS but i am confused where to validate on server side. Either to use mongooose for validations or don't do any validation on mongooose(just store) do validations only in server(Node/express using some modules) or validate on both server-level and database-level....????

What should i do pls help me choose which practice is best.....????

Thanks.

Upvotes: 2

Views: 1303

Answers (3)

Matan Reuven
Matan Reuven

Reputation: 95

You may also want to take a look at mongoose-validatorjs.

Upvotes: 0

Shivam Mishra
Shivam Mishra

Reputation: 1856

As a MEAN stack developer there are various ways to validate the form... 1.) AngularJs form validations 2.) Mongoose Validation 3.) Backend Validation ( Express validator ot nodeValidator )

==> Validation in mongoose

Ex.

var userSchema = new Schema({
  phone: {
    type: String,
    required: [true, 'User phone number required']
  },
  name: String,
  subDoc: [
    {
      newName:String,
      data:String
    }
  ]
});

Above code shows simple integration of mongoose validator.

Validation in mongoose schema can create problems when writing the document and worse situation can be generated when there are nested field and i am sure there will be. There are chances of modification of schema in such situation you to manage the validation, so much trouble i have faced..

So its a better IDEA to go with node validator or express validator which are super simple to use and provide lots of different type of validation options..

TRY node-validator, Express validator

js.com/package/node-validator

I personally suggest Express validator. which is simple and provide most of thing you need.

Upvotes: 2

Talha Awan
Talha Awan

Reputation: 4619

Banking just on mongoose validation is not enough. Your routes must be secured to not let invalid data pass through to mongoose validation.

The best place for this validation is middleware.

router.get('/', validateParameters, controller.index);

The function takes req, res and next. Call next if req parameters are valid, else respond with 400 status code. This way, only valid call reaches the end point.

function validateParameters(req, res, next){
  // if req.params/req.body/req.query is valid 
  // return next();
  // else return res.status(400).end;
}

As to actually how to validate, you can check express-validator package, which gives you lots of options to validate req body, query and params. One good option is creating a schema for each route and just passing that schema to validateParameters function and validating it with one of req.check(schema) (to check all), req.checkQuery(schema), req.checkBody(schema) orreq.checkParams(schema), depending on where your parameters are.

Upvotes: 0

Related Questions