repocrypts / Validator

Client-side javascript validator library ports from Laravel 5.2
MIT License
46 stars 22 forks source link
javascript laravel validation validator

Validator

npm Travis build Coverage Status FOSSA Status

A client-side JavaScript validation package, based on Laravel 5.2 validation.

Installation

  1. Included as global <script>, copy the Validator.js file inside dist directory to your project directory and reference it in the script tag. Or, you can use NPMCDN to reference it like so,

    <head>
        <script src="https://github.com/repocrypts/Validator/raw/master/public/js/Validator.js"></script>
        <!-- or using NPMCDN -->
        <script src="https://unpkg.com/Validator"></script>
    </head>
  2. Using NPM

    npm install Validator --save
    const Validator = require('Validator');

Usage

Supported Validation Rules

See validation rule usage in Laravel Documentation

Extending with Custom Validation Rules

The validator can be extended with custom rules

const rules = {
    id: 'required|mongoid'
};

function validateMongoId(name, value, params) {
    let hexadecimal = /^[0-9A-F]+$/i;
    return value && hexadecimal.test(value) && value.length === 24;
}

const v = Validator.make(data, rules);
v.extend('mongoid', validateMongoId, ':attr is not a valid mongo id');

if (v.passes()) {
    //...
}

validator.extend takes three required parameters:

The validation callback receives three parameters:

  1. name: the field name being validated
  2. value: the given value in the data
  3. params: Any parameters, passed after the colon in the rule definition.

Params defined ike so: rulename:min=10,max=15 would be passed in as an array: ['min=10', 'max=15']