Skip to content

kminek/async-validation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

async-validation

Simple asynchronous validation for Node.js

Usage

var Validation = require('async-validation');

// let's add some custom validator with db call
Validation.addValidator('uniqueUsername', function (callback, value, rule) {
  User.findOne({ username: value }, function (err, user) {
		if (err || user) {
			return callback('Username exists');
		}
		return callback(null);
	});
});

var data = {
  username: 'john',
  email: 'john@sample.com'
};

var rules = {
  username: [
    { validator: 'notEmpty', message: 'Username required' }, // custom error message
    { validator: 'uniqueUsername' }
  ]
  email: [
    { validator: 'notEmpty' },
    { validator: 'email' }
  ]
};

var options = {}; // optional

var v = new Validation(data, rules, options);

v.validate(function (err) {
  if (err) {
    console.log(err); // i.e. { username: 'Username exists' }
    return;
  }
  console.log('Ok');
});

Note that validation will stop processing other rules for a given field when first error is encountered. Also by default all textual input data is trimmed, pass { trim: false } option to disable this feature.

Default validators

notEmpty

{ validator: 'notEmpty' }

enum

{ validator: 'enum', values: ['male', 'female' }

regexp

{ validator: 'regexp', regexp: /^[a-zA-Z]{2}[a-zA-Z0-9_]{0,22}$/ }

email

{ validator: 'email' }

url

{ validator: 'url' }

same

{ validator: 'same', field: 'password_match' }

About

Simple asynchronous validation for Node.js

Resources

Stars

Watchers

Forks

Packages

No packages published