0.0.2 • Published 6 years ago

light-validate-js v0.0.2

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

npm version

Light Validate JS

This package provides light weight flexible JS validate helpers, supports async and group validation.

My goal for this repo is to avoid the binding of error messages & DOM elements and validations which would be more flexible to be used everywhere.

Installation

Light Validate JS module is available on the npm registry and can be installed using the

npm install light-validate-js

Example usage

  • RSVP setting:
Validator.validate.Promise = Promise;
  • To validate a single field
/**
 * 1st parameter is the value you want to validate,
 * 2nd parameter is the validator, which will carry
 * out the validations one by one basing on the
 * given order.
 *
 * It stops once one of the validations fail
 */
var validatePromise = Validator.validate.validate(fieldValue, [

    // You can pass an array [validateFunc, ...parameters]
    [function(value, param1, param2) {
        // validate pass
        return true;
    }, param1, param2],

    // Or pass an object like following:
    {
        validator: function(value, param1) {
            // validate fail
            return false;
        },
        parameters: [param1],
        errorMessage: 'This is error message!'
    },

    // validate fail and return error message directly
    [function() {
        return 'This is error message!';
    }],
    {
        validator: function(param1) {
            return 'This is error message!';
        },
        parameters: [param1]
    },

    // Async validate success
    [function() {
        return Promise.resolve(true);
    }],
    // Async validate fail
    [function() {
        return Promise.resolve(false);
    }],
    [function() {
        return Promise.resolve('This is error message!');
    }],
    [function() {
        return Promise.reject('This is error message!');
    }]
]);

validatePromise.then(function() {
    alert('Validate pass!');
}).catch(function(error) {
    alert(error.errorMessage);
});
  • To validate multiple fields
var validatePromise = Validator.validate.groupValidate({
    username: {
        value: 'jennie',
        validators: [
            [Validator.validator.Length, {min: 3, max: 10}]
        ]
    },
    email: {
        value: 'jennie.ji@hotmail.com',
        validators: [
            {
                validator: Validator.validator.Email,
                parameters: null,
                errorMessage: 'This is error message!'
            }
        ]
    }
}, isExitOnceError);

validatePromise.then(function() {
    alert('Validate pass!');
}).catch(function(errors) {
    alert(errors.map(function(err) {
        return err.name + ': ' + err.errorMessage;
    }).join('\n'));
});

Development Setup

  • download and install NodeJS
  • run npm install
  • run the tests using npm test
  • regenerate document: npm run docs

Development

Install nodeJs and run $: npm install.
Build to /disc: $: npm run build
Run unit testing: $: npm test
Regenerate document: $: npm run docs

API

Modules

Functions

Typedefs

validate

validate.validate(value, validators) ⇒ ValidatePromise

Kind: static method of validate
Access: protected

ParamType
value
validatorsArray.<Validator>

Example

validate('jennie.ji@shopeemobile.com', [
	[length, {min: 0}],
	[email]
]);

validate.groupValidate(group, exitOnceError) ⇒ ValidatePromise

Kind: static method of validate
Access: protected

ParamTypeDefault
groupObject.<object>
exitOnceErrorbooleantrue

Example

groupValidate({
	name: {
		value: 'Jennie',
		validators: [
			[length, {min: 3, max: 50}]
		]
	},
	email: {
		value: 'jennie.ji@shopeemobile.com',
		validators: [
			[length, {min: 0}],
			[email]
		]
	}
});

validator

validate(value, validators) ⇒ ValidatePromise

Kind: global function
Access: protected

ParamType
value
validatorsArray.<Validator>

Example

validate('jennie.ji@shopeemobile.com', [
	[length, {min: 0}],
	[email]
]);

groupValidate(group, exitOnceError) ⇒ ValidatePromise

Kind: global function
Access: protected

ParamTypeDefault
groupObject.<object>
exitOnceErrorbooleantrue

Example

groupValidate({
	name: {
		value: 'Jennie',
		validators: [
			[length, {min: 3, max: 50}]
		]
	},
	email: {
		value: 'jennie.ji@shopeemobile.com',
		validators: [
			[length, {min: 0}],
			[email]
		]
	}
});

Email(value) ⇒ boolean

Kind: global function

Param
value

Length(value, hash) ⇒ boolean

Kind: global function

ParamType
value
hashobject

Properties

NameType
hash.minnumber
hash.maxnumber
hash.excludeEdgeboolean

NumberRange(value, hash) ⇒ boolean

Kind: global function

ParamType
value
hashobject

Properties

NameType
hash.minnumber
hash.maxnumber
hash.excludeEdgeboolean

Number(value) ⇒ boolean

Kind: global function

Param
value

Regular(value, hash) ⇒ boolean

Kind: global function

ParamType
value
hashobject

Properties

NameType
hash.regularRegExp

Validator : object | Array.<(function()|object)>

Validator

Kind: global typedef
Properties

NameTypeDescription
Validator.validatorfunctionValidator function will always take validate value as 1st parameter. If it return true or promise resolve as true, means validate pass. If it return string or promise resolve as string, result will be treated as error message. All the other results will be passed to ValidateError.error.
Validator.parametersArrayOptional. Extra parameters for Validator.validator.
Validator.errorMessagestringOptional. Expected to be deprecated someday, since it's not as flexible as return error message by validator function directly (this is added in 0.0.2).

ValidateError : object

ValidateError

Kind: global typedef
Properties

NameTypeDescription
ValidateError.validatorfunctionvalidate function
ValidateError.parametersArrayvalidate function parameters
ValidateError.errorOriginal error response
ValidateError.errorMessagestringpredefined error message
Validator.namestringonly exists in group validate

ValidatePromise : Promise

ValidatePromise

Kind: global typedef
Properties

NameTypeDescription
ValidatePromise.thenfunctionValid
ValidatePromise.catchfuncitonInvalid. Parameter: errors - can be normal exceptions, or single/array of ValidateError