Git Product home page Git Product logo

validr's Introduction

Validr

Build Status

Framework agnostic Node.js validations. Inspired by validator, express-validator and validictorian.

Installation

npm install validr

Usage

If you have ever used express-validator you should feel right at home.

Here is an example using Express. Can be used similarly in any other framework.

var express = require('express'),
  Validr = require('validr'),
  trimBody = require('trim-body');

app = express();

app.use(express.bodyParser());
app.use(app.router);

app.post('/user', function (req, res){
  trimBody(req.body);

  // Expected 'req.body' object format
  // {
  //   name: {
  //     first: <first name>,
  //     last: <last name>
  //   },
  //   email: <email>,
  //   age: <age>,
  //   sex: <sex>,
  //   occupation: <occupation>
  // }


  // 1. Create an instance of Validr.

  var validr = new Validr(req.body);


  // 2. Validations

  validr
    // use string with dot-notation to validate nested fields
    .validate('name.first', 'First Name is required.')
    .isLength(1);

  validr
    // you can also use an array to validate nested fields
    .validate(['name', 'last'], 'Last Name is required.')
    .isLength(1);

  validr
    // an object can be used to set separate validation messages for validators.
    .validate('email', {
      isLength: 'Email is required.',
      isEmail: 'Email must be valid.'
    })
    // validators are chainable
    .isLength(1).isEmail(); 

  validr
    // validate method accepts a 3rd parameter which is an options object
    // age will not be validated if '', `null` or undefined
    .validate('age', 'Age must be a number.', {ignoreEmpty: true})
    .isNumeric();

  validr
    .validate('sex', 'Sex must be M (male) or F (female).')
    .isIn(['M', 'F']).isLength(1);


  // 3. Check for errors.

  var errors = validr.validationErrors();

  if (errors) return res.json(errors);



  // ...
  // Process req.body however you want. Example: save to db.
});


app.listen(3000);

Validate

Validating fields is similar to express-validator's assert.

Differences between validate and assert.

  • No notEmpty and len methods. Use isLength.
  • Nested fields are targeted with a dot-notation string or array. Example: 'name.first' or ['name', 'first'].

You can pass a 3rd parameter to validate to ignore validation if field is not supplied. See usage's age validation

Validation errors

You can get errors in two ways. Similar to express-validator.

var errors = validr.validationErrors();
var mappedErrors = validr.validationErrors(true);

errors:

[
  {param: "email", msg: "Email is required.", value: "<received input>"},
  {param: "email", msg: "Email must be valid.", value: "<received input>"},
  {param: "age", msg: "Age must be a number.", value: "<received input>"}
]

mappedErrors:

{
  email: {
    param: "email",
    msg: "Email must be valid.",
    value: "<received input>"
  },
  age: {
    param: "age",
    msg: "Age is required.",
    value: "<received input>"
  }
}

Extending with custom validators

Add custom validator functions to an object, which is the second parameter when instantiating Validr.

var validr = new Validr(body, {
  isNotExampleEmail: function(str) {
    return !/@example.com/.test(str);
  }
});

validr.validate('email', {
  isLength: 'Email is required.',
  isEmail: 'Email must be valid',
  isNotExampleEmail: 'Email must NOT be @example.com.'
  }).isLength(1).isEmail().isNotExampleEmail();

Tests

npm install -g mocha

Then,

npm test

Contributors

License

MIT

validr's People

Contributors

mocheng avatar samora avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

validr's Issues

Support custom validators

Validator supports extending it with custom validators. It would be nice if validr supported the same API.

How to validate array ?

Ideally, Validr should work for below code

var data = {
   emails: ['[email protected]', '[email protected]']
};

var validr = new Validr(data);
validr.validate('emails', 'need emails').isLength(2).isEmail();

However, current validr doesn't recognise array properties and report error for this case.

`ignoreEmpty` might not be enough

Even though there is a ignoreEmpty to ignore empty field, it doesn't help for Number type field.

Since number type is always empty for lodash _.isEmpty method, it cannot correctly detect it.

A ignoreUndefined would help.

Is it better to not require validator method starting with `is`?

In my team, this has already happened twice. Developer name extended validator as checkChinesePhoneNumber and it doesn't work.

It costs half an hour to figure out that all validator methods must start with is, as below code states.

https://github.com/samora/validr/blob/master/lib/validr.js#L27-L30

    // Verify valid validator method.
    var notValidator = (method.slice(0, 2) !== 'is'
      && method !== 'equals'
      && method !== 'contains'
      && method !== 'matches');

To save more time for validr users, would it better to drop this limitation?

I do not know how to explain it

there's my system:
Linux AY130708201113505828Z 3.2.0-65-generic #98-Ubuntu SMP Wed Jun 11 20:27:07 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

there's my node_version:
v0.10.32

there;s my npm_version:
1.4.28

there's is my test file: // l know it is a error file
var Validr = require('Validr');

can't find model Validr;

but the test file in my mac is ok!!!!!!!!!

get validator methods

How do I get the validator model methods ? because l want to overwrite some method for my work;
thanks

How to validate fields in array type subfields?

For example, there is params defined as below

var params = {
    users: [
         {
              name: 'mike',
              gender: 'M'
         },
         {
              name: 'tom',
              gender: 'M'
         }
    ]
};

Currently, there is no way to validate the first user's name like
validr.validate('users[0].name', 'first user should have name').isLength(1).

How to extend current method to support this?

add validateIfExists method

In my practical programming context, there are such kind of code

function some_action(req, res) {
   var validr = new Validr(req.body);
   if (req.body.phone_num) { 
       validr.validate('phone_num', 'phone number  should be valid').isNumeric();
   }

}

Some arguments, suck as phone_num in above code is optional. So, we only need to validate it if it exists. However, having if statement to check its existence introduce increased cyclomatic complexity.

If there an validateIfExists function to do validation only given field exists or empty. That would be great.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.