prg-validator

0.4.0 • Public • Published

Pragonauts Isomorphic Validator

Node.js/Browser validation utility, which allows us to use single validator across multiple endpoints. Uses (npm/validator)[https://www.npmjs.com/package/validator] rules.

const Validator = require('prg-validator');
 
 
class UserValidator extends Validator {
 
    constructor () {
 
        super();
 
        this.CONTEXT_REGISTER_WITH_PASSWORD = 'registerWithPassword';
 
        this.CONTEXT_CREATE = 'create';
 
        this.CONTEXT_UPDATE = 'update';
 
        this.add('email')
            .if([this.CONTEXT_REGISTER_WITH_PASSWORD, this.CONTEXT_CREATE])
                .isRequired('Email is required')
            .endIf()
            .isEmail('The email has to be valid');
 
        this.add('username')
            .if([this.CONTEXT_CREATE])
                .isRequired('The username is required')
            .endIf()
            .is('isLength', 'The username has to be at least 1 character long.', {
                min: 1
            });
 
        this.add('password')
            .if([
                this.CONTEXT_REGISTER_WITH_PASSWORD,
                this.CONTEXT_SET_PASSWORD,
                this.CONTEXT_CREATE
            ])
                .isRequired('Password is required')
            .endIf()
            .if(val => val)
                .is('isLength', 'The password has to be at least 7 characters long.', { min: 7 })
            .endIf();
    }
 
}
 
const catchAllErrors = false;
const validator = new UserValidator();
 
validator.validate({ email: 'ab' }, validator.CONTEXT_UPDATE, catchAllErrors)
    .then((validData) => {
        // successful validation, data are filtered
    })
    .catch((e) => {
        // e instanceof ValidationError, or ValidationError[] when catchAllErrors is true
    });

API

Classes

ValidationError
Validator
Rule
Rule

ValidationError

Kind: global class

validationError.message

Kind: instance property of ValidationError
Properties

Name Type Description
message string validator message

validationError.property

Kind: instance property of ValidationError
Properties

Name Type Description
property string name of the property

validationError.type

Kind: instance property of ValidationError
Properties

Name Type Description
type string validator name (or function)

Validator

Kind: global class

new Validator()

Single entity validator. Just extend this class

validator.add(property) ⇒ Rule

Add another property to validate

Kind: instance method of Validator

Param Type Description
property string name of the property

validator.validateProp(property, value, [catchAllErrors], [data]) ⇒ Promise

Validate single property

Kind: instance method of Validator

Param Type Default Description
property string name of property
value any
[catchAllErrors] boolean false stop on first error or return all found errors
[data] object {} other data to use for conditions

validator.validate(data, [context], [catchAllErrors]) ⇒ Promise.<object>

Kind: instance method of Validator

Param Type Default Description
data object
[context] string null name of validation context, which limits validaton
[catchAllErrors] boolean false stop on first error or return all found errors

Rule

Kind: global class

new Rule()

Single attribute rule contructor

new Rule(rules)

Creates an instance of Rule.

Param Type
rules Array.<object>

rule.is(action, [message], [args]) ⇒ this

Add any validator to rule

Kind: instance method of Rule

Param Type Default Description
action string | function name of the validator
[message] any error message
[args] any arguments to pass to the validator

Example

validator.add('property')
    .is(value => value.match(/xy/))

rule.to(action, [args]) ⇒ this

Adds sanitizer (filter) which converts value to different type

Kind: instance method of Rule

Param Type Description
action string | function
[args] any arguments to pass to the validator

Example

validator.add('property')
    .to(value => parseInt(value, 10));

rule.if(action) ⇒ this

Adds confition. It can filter validators by context or with custom function

Kind: instance method of Rule

Param Type Description
action string | array | function context name, array of context names or function

Example

validator.add('property')
    .if((value, data, context) => data.otherProperty)
        .isRequire('Should be filled')
    .endIf();

rule.endIf() ⇒ this

Ends condition

Kind: instance method of Rule

rule.default(value) ⇒ this

Sets default value, when item is not filled. Empty string is considered as a value.

Kind: instance method of Rule

Param Type
value any

rule.contains(string, [message]) ⇒ this

Searches for occourence of the string

Kind: instance method of Rule

Param Type Default
string string
[message] string null

rule.isNumeric([message]) ⇒ this

Input shoud be numeric

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isEmail([message]) ⇒ this

Input should be the email

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isUrl([message], [options]) ⇒ this

Validates non-empty strings as url

Kind: instance method of Rule

Param Type Default
[message] string null
[options] Object

Example

validator.isUrl('Message', {
      protocols: ['http','https','ftp'],
      require_tld: true,
      require_protocol: false,
      require_host: true,
      require_valid_protocol: true,
      allow_underscores: false,
      host_whitelist: false,
      host_blacklist: false,
      allow_trailing_dot: false,
      allow_protocol_relative_urls: false
 })

rule.isRequired([message]) ⇒ this

Input is required

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isRequiredIfPresent([message]) ⇒ this

Input is required, only when atributte is not missing (not undefined)

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isFileMime(message, types) ⇒ this

Validates File mime types. Compatible with browser-side File class and prg-uploader

Kind: instance method of Rule

Param Type Description
message string error message
types Array.<string> | string | regexp | Array.<regexp> validate theese types

rule.isFileMaxLength(message, types) ⇒ this

Validates File mime types. Compatible with browser-side File class and prg-uploader

Kind: instance method of Rule

Param Type Description
message string error message
types Array.<string> | string | regexp | Array.<regexp> validate theese types

rule.toInt([message]) ⇒ this

Makes the integer from an input

Kind: instance method of Rule

Param Type Default
[message] string null

rule.toBoolean([message]) ⇒ this

Makes the boolean from an input

Kind: instance method of Rule

Param Type Default
[message] string null

rule.toFileData() ⇒ this

Substracts data from the file. It actually extracts ".data" property from object, but just on the serverside

Kind: instance method of Rule

Rule

Kind: global class

new Rule()

Single attribute rule contructor

new Rule(rules)

Creates an instance of Rule.

Param Type
rules Array.<object>

rule.is(action, [message], [args]) ⇒ this

Add any validator to rule

Kind: instance method of Rule

Param Type Default Description
action string | function name of the validator
[message] any error message
[args] any arguments to pass to the validator

Example

validator.add('property')
    .is(value => value.match(/xy/))

rule.to(action, [args]) ⇒ this

Adds sanitizer (filter) which converts value to different type

Kind: instance method of Rule

Param Type Description
action string | function
[args] any arguments to pass to the validator

Example

validator.add('property')
    .to(value => parseInt(value, 10));

rule.if(action) ⇒ this

Adds confition. It can filter validators by context or with custom function

Kind: instance method of Rule

Param Type Description
action string | array | function context name, array of context names or function

Example

validator.add('property')
    .if((value, data, context) => data.otherProperty)
        .isRequire('Should be filled')
    .endIf();

rule.endIf() ⇒ this

Ends condition

Kind: instance method of Rule

rule.default(value) ⇒ this

Sets default value, when item is not filled. Empty string is considered as a value.

Kind: instance method of Rule

Param Type
value any

rule.contains(string, [message]) ⇒ this

Searches for occourence of the string

Kind: instance method of Rule

Param Type Default
string string
[message] string null

rule.isNumeric([message]) ⇒ this

Input shoud be numeric

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isEmail([message]) ⇒ this

Input should be the email

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isUrl([message], [options]) ⇒ this

Validates non-empty strings as url

Kind: instance method of Rule

Param Type Default
[message] string null
[options] Object

Example

validator.isUrl('Message', {
      protocols: ['http','https','ftp'],
      require_tld: true,
      require_protocol: false,
      require_host: true,
      require_valid_protocol: true,
      allow_underscores: false,
      host_whitelist: false,
      host_blacklist: false,
      allow_trailing_dot: false,
      allow_protocol_relative_urls: false
 })

rule.isRequired([message]) ⇒ this

Input is required

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isRequiredIfPresent([message]) ⇒ this

Input is required, only when atributte is not missing (not undefined)

Kind: instance method of Rule

Param Type Default
[message] string null

rule.isFileMime(message, types) ⇒ this

Validates File mime types. Compatible with browser-side File class and prg-uploader

Kind: instance method of Rule

Param Type Description
message string error message
types Array.<string> | string | regexp | Array.<regexp> validate theese types

rule.isFileMaxLength(message, types) ⇒ this

Validates File mime types. Compatible with browser-side File class and prg-uploader

Kind: instance method of Rule

Param Type Description
message string error message
types Array.<string> | string | regexp | Array.<regexp> validate theese types

rule.toInt([message]) ⇒ this

Makes the integer from an input

Kind: instance method of Rule

Param Type Default
[message] string null

rule.toBoolean([message]) ⇒ this

Makes the boolean from an input

Kind: instance method of Rule

Param Type Default
[message] string null

rule.toFileData() ⇒ this

Substracts data from the file. It actually extracts ".data" property from object, but just on the serverside

Kind: instance method of Rule

Package Sidebar

Install

npm i prg-validator

Weekly Downloads

0

Version

0.4.0

License

MIT

Last publish

Collaborators

  • pragonauts