Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate and handle a form in Express (NodeJS)

Tags:

Is there a preferred form handling and validation library for Express?

I'm really looking for a similar level of abstraction as is found in Django forms - i.e. validation and error reporting in the template.

If the same validation could be used on the client side, that would be great.

Has anyone used, or written, anything good?

like image 354
fadedbee Avatar asked Apr 05 '11 16:04

fadedbee


People also ask

What is Express validator in NodeJS?

According to the official website, Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.

How do you validate a form?

Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value.

What is validation and sanitization in NodeJS?

One method of preventing SQL injection is to sanitize inputs. Input sanitization is a cybersecurity measure of checking, cleaning, and filtering data inputs before using them. validator. js is a library of string validators and sanitizers that can be used server-side with Node.


2 Answers

It looks like there's a module for this located at https://github.com/caolan/forms. I've never used it, but it seems fairly full featured.

like image 200
Zikes Avatar answered Oct 07 '22 01:10

Zikes


This also looks viable and is still being developed: https://github.com/ctavan/express-validator

Here's an example of validating a form submission (login post request):

exports.login.post = function(req, res){
  req.assert('username', 'Enter username').notEmpty();
  req.assert('password', 'Enter password').notEmpty();
  res.locals.err = req.validationErrors(true);

  if ( res.locals.err ) {
    if ( req.xhr ) {
      res.send(401, { err: res.locals.err });
    } else {
      res.render('login', { err: res.locals.err });
    }

    return;
  }

 //authenticate user, data is valid
};
like image 27
chovy Avatar answered Oct 07 '22 00:10

chovy