0.4.0 • Published 7 years ago

prg-validator v0.4.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

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

Kind: global class

validationError.message

Kind: instance property of ValidationError
Properties

NameTypeDescription
messagestringvalidator message

validationError.property

Kind: instance property of ValidationError
Properties

NameTypeDescription
propertystringname of the property

validationError.type

Kind: instance property of ValidationError
Properties

NameTypeDescription
typestringvalidator 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

ParamTypeDescription
propertystringname of the property

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

Validate single property

Kind: instance method of Validator

ParamTypeDefaultDescription
propertystringname of property
valueany
catchAllErrorsbooleanfalsestop on first error or return all found errors
dataobject{}other data to use for conditions

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

Kind: instance method of Validator

ParamTypeDefaultDescription
dataobject
contextstringnullname of validation context, which limits validaton
catchAllErrorsbooleanfalsestop 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.

ParamType
rulesArray.<object>

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

Add any validator to rule

Kind: instance method of Rule

ParamTypeDefaultDescription
actionstring | functionname of the validator
messageanyerror message
argsanyarguments 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

ParamTypeDescription
actionstring | function
argsanyarguments 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

ParamTypeDescription
actionstring | array | functioncontext 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

ParamType
valueany

rule.contains(string, message) ⇒ this

Searches for occourence of the string

Kind: instance method of Rule

ParamTypeDefault
stringstring
messagestringnull

rule.isNumeric(message) ⇒ this

Input shoud be numeric

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isEmail(message) ⇒ this

Input should be the email

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isUrl(message, options) ⇒ this

Validates non-empty strings as url

Kind: instance method of Rule

ParamTypeDefault
messagestringnull
optionsObject

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

ParamTypeDefault
messagestringnull

rule.isRequiredIfPresent(message) ⇒ this

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

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isFileMime(message, types) ⇒ this

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

Kind: instance method of Rule

ParamTypeDescription
messagestringerror message
typesArray.<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

ParamTypeDescription
messagestringerror message
typesArray.<string> | string | regexp | Array.<regexp>validate theese types

rule.toInt(message) ⇒ this

Makes the integer from an input

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.toBoolean(message) ⇒ this

Makes the boolean from an input

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

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.

ParamType
rulesArray.<object>

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

Add any validator to rule

Kind: instance method of Rule

ParamTypeDefaultDescription
actionstring | functionname of the validator
messageanyerror message
argsanyarguments 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

ParamTypeDescription
actionstring | function
argsanyarguments 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

ParamTypeDescription
actionstring | array | functioncontext 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

ParamType
valueany

rule.contains(string, message) ⇒ this

Searches for occourence of the string

Kind: instance method of Rule

ParamTypeDefault
stringstring
messagestringnull

rule.isNumeric(message) ⇒ this

Input shoud be numeric

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isEmail(message) ⇒ this

Input should be the email

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isUrl(message, options) ⇒ this

Validates non-empty strings as url

Kind: instance method of Rule

ParamTypeDefault
messagestringnull
optionsObject

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

ParamTypeDefault
messagestringnull

rule.isRequiredIfPresent(message) ⇒ this

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

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.isFileMime(message, types) ⇒ this

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

Kind: instance method of Rule

ParamTypeDescription
messagestringerror message
typesArray.<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

ParamTypeDescription
messagestringerror message
typesArray.<string> | string | regexp | Array.<regexp>validate theese types

rule.toInt(message) ⇒ this

Makes the integer from an input

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

rule.toBoolean(message) ⇒ this

Makes the boolean from an input

Kind: instance method of Rule

ParamTypeDefault
messagestringnull

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

0.4.0

7 years ago

0.4.0-pre2

7 years ago

0.4.0-pre1

7 years ago

0.3.1

7 years ago

0.3.0

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago