npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-validator-helper

v1.0.1

Published

simple express-validator wrapper for easier work with validation error handling

Downloads

16

Readme

express-validator-helper

img img img img img img

Simple express-validator wrapper for easier work with validation error handling.

img

Installation

$ npm i express-validation-helper -S
// add expressValidator before helper
app.use(expressValidator());
app.use(expressValidatorHelper());

Usage

Just do a check with express-validator as usual. Then instead req.validationErrors(true) call req.validate(). This method returns a Validator object.

Validator object

add(fieldName, msg)

Add error with msg to fieldName.

isValid()

Returns true if all data is valid. Otherwise false.

errors

Object with all validation errors. It should be used only if the isValid method returns false.

Values contain an array with a list of errors. Example:

{
  email: ['required', 'invalid format', 'already taken'],
  password: ['required']
}

Customization

You can pass name option to middleware with a custom method name:

app.use(expressValidatorHelper({
  name: 'doValidate'
});

// ...

var validator = req.doValidate();

Before & After

Confirmation handler example.

Before

exports.create = function(req, res, next) {
  // checks with reverse order
  req.assert('email', 'invalid format').isEmail();
  req.assert('email', 'required').notEmpty();

  var errors = req.validationErrors(true);
  var email = req.body.email;

  return User.findOne({
    email: new RegExp('^' + email + '$', 'i')
  }, function(err, user) {
    if (err) { return next(err); }

    if (user && user.isEmailConfirmed === true && !errors.email) {
      errors = errors || {};
      errors.email = {
        param: 'email',
        msg: 'you account already confirmed',
        value: email
      };
    }

    if (!user && !errors.email) {
      errors = errors || {};
      errors.email = {
        param: 'email',
        msg: 'user with that email not found'
      };
    }

    if (!_.isEmpty(errors)) {
      return res.render('confirmations/new', {
        errors: errors,
        values: req.body
      });
    }

    // ... success
  });
};

After

exports.create = function(req, res, next) {
  // checks with normal order
  req.assert('email', 'required').notEmpty();
  req.assert('email', 'invalid format').isEmail();

  // call validate method on `req` object
  var validator = req.validate();
  var email = req.body.email;

  return User.findOne({
    email: new RegExp('^' + email + '$', 'i')
  }, function(err, user) {
    if (err) { return next(err); }

    if (user && user.isEmailConfirmed === true) {
      // add errror for email field
      validator.add('email', 'you account already confirmed');
    }

    if (!user && !errors.email) {
      validator.add('email', 'user with that email not found')
    }

    // check if user data is not valid
    if (!validator.isValid()) {
      return res.render('confirmations/new', {
        errors: validator.errors,  // pass errors property to views
        values: req.body
      });
    }

    // ... success
  });
};

Reason

express-validator (Validator.js middleware for Express.js) is wonderful tool for validating user input. But it does not allow to define custom async validators. For example we want to check if email is already taken on signup page. Ok, we can add errors manually to req.validationErrors() result. And here we are faced with several problems:

req.validationErrors() result

express-validator provides two ways to get a result - as an array or object.

Array is not very useful if you want to display an error for each field separately. It is not for us.

Object contains only the last error:

req.assert('email', __('required')).notEmpty();
req.assert('email', __('invalid format')).isEmail();

var errors = req.validationErrors(true);

Here the errors will contain message for format validation instead notEmpty() check. So you have to do the checking in reverse order. This is the first problem.

Adding errors

req.validationErrors(true) can return null or object with errors and we should check it. Also error for a particular field may already be in the object and we should check it too:

req.assert('email', __('invalid format')).isEmail();
req.assert('email', __('required')).notEmpty();

var errors = req.validationErrors(true);

User.findOne({ email: req.body.email }, function(err, existsUser) {
  if (err) { return next(err); }

  if (existsUser && !errors.email) {
    errors = errors || {};
    errors.email = {
      param: 'email',
      msg: 'already taken',
      value: req.body.email
    }
  }
});

If we do not check this, our error will appear even when unfilled or incorrect e-mail address.

It becomes routine, when we do more of checks like this.

Tests

  • npm test
  • npm run-script test-cov

License

MIT