GithubHelp home page GithubHelp logo

uranus's Introduction

Logo

Uranus is a wrapper validation utility over chriso's awesome validator.js with some extra extension methods.

Build Status npm version tag npm Code Climate

Installation:

 $ npm install --save uranus

Note: 2.x is written in Node 4x so its not compatible with previous versions of Node. For previous versions, install 1.x:

 $ npm install --save [email protected]

Tests:

To execute tests:

 # clone the repo and change directory
 $ git clone https://github.com/umayr/uranus.git && cd $_

 # install local dependencies
 $ npm install
 
 # run tests
 $ npm test

Usage:

After installing uranus, you can simply use it as:

 const Uranus = require('uranus');
 let result = Uranus.validateAll([
 {
    value: '@foo.com',
    rules: {
      isEmail: true,
      len: [15, 100]
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: true,
      isLowercase: true,
      notContains: 'Net'
    }
 }]);
 
 console.log(result.isValid()) // false

There are several ways to apply validations. For bulk validation you can use validateAll which supports both array and object.

 const Uranus = require('uranus');
 
 // For Arrays.
 let result = Uranus.validateAll([
 {
    value: '[email protected]',
    rules: {
      isEmail: true
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: true,
    }
 }]);
 console.log(result.isValid()) // true
 
 // For objects.
 let src = {
    name: 'Neptune',
    email: '[email protected]'
  };
  
  let rules = {
    name: {
      isAlpha: true
    },
    email: {
      isEmail: true
    }
  }
let result = Uranus.validateAll(src, rules);
console.log(result.isValid()) // true

By default Uranus generates subject less error messages itself with the help of Cressida. For e.g:

let rules = {
   isEmail: true
};
Uranus.validateOne('foo@..!!.com', rules);

// ['should be a valid email address.']

By default these messages are subjectless. To specify a name, you can do something like this:

// For `validateOne()`:

let rules = {
   isEmail: true
};
Uranus.validateOne({value: 'foo@..!!.com', name: 'Foo'}, rules);
// ['Foo should be a valid email address.']

// For `validateAll()` with an array:

let result = Uranus.validateAll([
        {
          value: 'foo',
          name: 'Foo',
          rules: {
            isEmail: true
          }
        }
      ], {
        includeName: true
      });
// ['Foo should be a valid email address.']

// For `validateAll()` with an object:

let src = {
    email: {
       name: 'Foo',
       value: 'foo@!!!.com'
   }
  };

  let rules = {
    email: {
      isEmail: true
    }
  }
Uranus.validateAll(src, rules);
// ['Foo should be a valid email address.']

This feature can be turned off with includeName set to false in options moreover you can set your own error messages.

let result = Uranus.validateAll([
 {
    value: '@foo.com',
    rules: {
      isEmail: {
        args: true,
        msg: 'Boo! email is invalid'
      },
      len: {
        args: [15, 100],
        msg: 'You\'re either too large or too small.'
      }
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: {
        args: true,
        msg: 'meh, only letters, k?'
      },
      isLowercase: {
        args: true,
        msg: 'only lowercase, babes.'
      },
      notContains: {
        args: 'Net',
        msg: 'No fishin\''
      }
    }
 }]);

For validating one single value, you can use validateOne as:

let value = '[email protected]';
let rules = {
   isEmail: true,
   notNull: true
};

Uranus.validateOne(value, rules);

Both validateOne & validateAll methods can also be accessed by creating an instance of Uranus. For example:

 const Uranus = require('uranus');
 let validator = new Uranus();
 
 // validateAll
 let result = validator.validateAll([
 {
    value: '[email protected]',
    rules: {
      isEmail: true
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: true,
    }
 }]);
 console.log(result.isValid()) // true
 
 // validateOne
 let value = '[email protected]';
 let rules = {
  isEmail: true,
  notNull: true
 };
  
 let result = validator.validateOne(value, rules);
 console.log(result.isValid()) // true
 

By default validateAll validates all the rules for all value sets but if you set progressive to true while creating Uranus instance, it will stop iterating through rules when one fails. In that way you can get only one error message for one value instead of getting all, for example:

let validator = new Uranus({ progressive: true });
let result = validator.validateAll([
 {
    value: '@foo.com',
    rules: {
      isEmail: {
        args: true,
        msg: 'Boo! email is invalid'
      },
      len: {
        args: [15, 100],
        msg: 'You\'re either too large or too small.'
      }
    }
 }]);
 
 console.log(result.getAllMessages())
 // ["Boo! email is invalid"]

Note: In case of static methods, options can be provided as the last argument.

Later you can get all of these messages by getAllMessages() method. For example,

  let msgs = result.getAllMessages();
  console.log(msgs)
  // ["Boo! email is invalid", "You're either too large or too small.", "meh, only letters, k?", "only lowercase, babes.", "No fishin'"]

You can also get message for one specific rule by:

  let msg = result.getMessage(0, 'isEmail'); // where 0 is the index of provided array.
  console.log(msg) // Boo! email is invalid

In order to get all rules for one value you can use getItem() method, like:

  let check = result.getItem(0);
  
  console.log(check.isEmail.isValid()) // false
  console.log(check.isEmail.getMessage()) // Boo! email is invalid
  
  console.log(check.len.isValid()) // false
  console.log(check.len.getMessage()) // You're either too large or too small.

Note: You can get whole ValidationItem by using getRule().

Supported Rules:

As mentioned above, Uranus acts like a wrapper to validator.js so it supports all validations currently provided by validator.js. In addition to that, there are several extra validations rules that Uranus provides out of the box. Some common validations along with their args are as follows:

  is: ["^[a-z]+$",'i'],       // will only allow letters
  is: /^[a-z]+$/i,            // same as the previous example using real RegExp
  not: ["[a-z]",'i'],         // will not allow letters
  isEmail: true,              // checks for email format ([email protected])
  isUrl: true,                // checks for url format (http://foo.com)
  isIP: true,                 // checks for IPv4 (129.89.23.1) or IPv6 format
  isIPv4: true,               // checks for IPv4 (129.89.23.1)
  isIPv6: true,               // checks for IPv6 format
  isAlpha: true,              // will only allow letters
  isAlphanumeric: true        // will only allow alphanumeric characters, so "_abc" will fail
  isNumeric: true             // will only allow numbers
  isInt: true,                // checks for valid integers
  isFloat: true,              // checks for valid floating point numbers
  isDecimal: true,            // checks for any numbers
  isLowercase: true,          // checks for lowercase
  isUppercase: true,          // checks for uppercase
  notNull: true,              // won't allow null
  isNull: true,               // only allows null
  notEmpty: true,             // don't allow empty strings
  equals: 'specific value',   // only allow a specific value
  contains: 'foo',            // force specific substrings
  optional: ['isUrl']         // validate the rule provided in second parameter if first param is not null
  notIn: [['foo', 'bar']],    // check the value is not one of these
  isIn: [['foo', 'bar']],     // check the value is one of these
  notContains: 'bar',         // don't allow specific substrings
  len: [2,10],                // only allow values with length between 2 and 10
  isUUID: 4,                  // only allow uuids
  isDate: true,               // only allow date strings
  isAfter: "2011-11-05",      // only allow date strings after a specific date
  isBefore: "2011-11-05",     // only allow date strings before a specific date
  max: 23,                    // only allow values
  min: 23,                    // only allow values >= 23
  isArray: true,              // only allow arrays
  isCreditCard: true          // check for valid credit card numbers

Checkout Validator.js project for more details on supported validations.

Note: If a rule is supported by validator.js but it doesn't work properly in Uranus, please feel free to report an issue.

Custom Rules:

Additional rules can be added while instantiating Uranus, for e.g.

  let validator = new Uranus({
      extensions: {
        hasFoo(str) {
          return str.match(/foo/);
        }
      }
    });
  let response = validator.validateAll([{
      value: 'foo',
      rules: {
        hasFoo: true
      }
    }]);
        
  response.isValid() // true

If you want to use predefined rules in your custom rule, it can be done as:

  let validator = new Uranus({
      extensions: {
        isLowercaseAlpha(str) {
          // Here `this` refers to the validator instance.
          // Therefore, all built-in validators will be available here.
          
          return this.isAlpha(str) && this.isLowercase(str)
        }
      }
    });
  let response = validator.validateAll([{
      value: 'foobar1',
      rules: {
        isLowercaseAlpha: true
      }
    }]);
        
  response.isValid() // false

Parameters passed from a rule can be accessed as additional arguments in the extension method:

  let validator = new Uranus({
      extensions: {
        range(str, min, max) {
          return str.length > min && str.lenght < max;
        }
      }
    });
  let response = validator.validateAll([{
      value: 'cat',
      rules: {
        range: [1, 10]
      }
    }]);
        
  response.isValid() // true

License:

The MIT License (MIT)

Copyright (c) 2015 Umayr Shahid <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

uranus's People

Stargazers

Mashhood Rastgar avatar Umayr Shahid avatar  avatar Uzair Ali Khan avatar

Watchers

James Cloos avatar Umayr Shahid avatar Muhammad Umair Khan avatar  avatar

uranus's Issues

Generate messages with name.

Uranus supports only subjectless messages. For e.g:

var rules = {
   isEmail: true
};
Uranus.validateOne('foo@..!!.com', rules);

// ['should be a valid email address.']

There must be a way to provide name and get complete error messages, like:

var rules = {
   isEmail: true
};
Uranus.validateOne({value: 'foo@..!!.com', name: 'Foo'}, rules);

// ['Foo should be a valid email address.']

The functionality must be backward compatible meaning it should work either way if I provide a name or not.

For validateAll, there should be another property to specify a name, like:

var result = Uranus.validateAll([
        {
          value: 'foo',
          name: 'Foo',
          rules: {
            isEmail: true
          }
        }
      ], {
        includeName: true
      });

// ['Foo should be a valid email address.']

There should be an option to turn this off with a flag like includeName. The default value should be true but if you don't provide a name it should generate subjectless message.

I don't see how it should work with validateAll when an object is provided. The less elegant would be:

var src = {
    email: {
       name: 'Foo',
       value: 'foo@!!!.com'
   }
  };

  var rules = {
    email: {
      isEmail: true
    }
  }
Uranus.validateAll(src, rules);

// ['Foo should be a valid email address.']

`validateOne` & `validateAll` should be static methods.

As for now, validateOne & validateAll are instance methods. You need to create an instances in order to use them. Such as:

var Uranus = require('uranus');
var validator = new Uranus();
var result = validator.validateAll([
{
   value: '@foo.com',
   rules: {
     isEmail: true,
     len: [15, 100]
   }
},{
   value: 'Neptune',
   rules: {
     isAlpha: true,
     isLowercase: true,
     notContains: 'Net'
   }
}]);

In order to be more clean it should be more like:

var Uranus = require('uranus');
var result = Uranus.validateAll([
 {
    value: '@foo.com',
    rules: {
      isEmail: true,
      len: [15, 100]
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: true,
      isLowercase: true,
      notContains: 'Net'
    }
 }]);

Not much difference but still.

Add `validate` method that should be bound to check only one rule.

In current API, validateAll takes an array; there is no other way to determine the validation of a single item.

There should be a method which verifies only one value according to the provided set of rules.

Proposed method signature and basic usage:

var value = '[email protected]';
var rules = {
   isEmail: true,
   notNull: true
};
validator.validate(value, rules);

It should return the same ValidationResult Instance alongwith an array of ValidationItem.

Validity issues

Uranus overwrites validity with the last provided value and ignores validity of previous values either they are true or false.

For Example:
name = " ", lastname = " " city = "Alaska"

and required is set for all values then uranus sets validity equal to true because validity of last provided value (city) is true so all previous validations are overwritten with last one.

`getAllMessages` doesn't work with `validateOne`

Throws an error:

TypeError: undefined is not a function
      at ValidationResult.getAllMessages (D:/experiments/uranus/src/classes/result.js:85:27)
      at exec (D:/experiments/uranus/tests/index.js:39:19)
      at D:/experiments/uranus/tests/index.js:48:5
      at Array.forEach (native)
      at test (D:/experiments/uranus/tests/index.js:47:36)
      at Context.<anonymous> (D:/experiments/uranus/tests/index.js:86:7)

Support for Objects in `validateAll` method.

Currently, validateAll requires an array, like:

var validator = new Uranus();
 var result = validator.validateAll([
 {
    value: '@foo.com',
    rules: {
      isEmail: true,
      len: [15, 100]
    }
 },{
    value: 'Neptune',
    rules: {
      isAlpha: true,
      isLowercase: true,
      notContains: 'Net'
    }
 }]);

It should also support an object based validation, proposed usage:

var Uranus = require('uranus');
var validator = new Uranus();

var obj = {
  firstName: 'umayr',
  lastName: 'shahid',
  email: '[email protected]'
};

var rules = {
  firstName: {
    notNull: true,
    isAlpha: true,
    len: [10, 100]
  },
  lastName: {
    notNull: true,
    isAlpha: true,
    len: [10, 100]
  },
  email: {
    notNull: true,
    isEmail: true
  }
}
validator.validateAll(obj, rules);

Make `validate` method private.

Currently this method:

Uranus.prototype.validate = function validate(value, test, rule) {
  if (typeof this.validator[rule] !== 'function') {
    throw new Error('Invalid validator function: ' + rule);
  }

  var validatorArgs = test.args || test;

  if (!Array.isArray(validatorArgs)) {
    if (rule === 'isIP') {
      validatorArgs = [];
    } else {
      validatorArgs = [validatorArgs];
    }
  } else {
    validatorArgs = validatorArgs.slice(0);
  }
  return this.validator[rule].apply(validator, [value].concat(validatorArgs));
};

is a part of prototype, hence it is exposed to every uranus instance which is not correct because its only purpose is to be the proxy of validator.js.

This should not be attached to prototype, instead it should be private method.

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.