2.0.1 • Published 5 months ago

form-schema-validation v2.0.1

Weekly downloads
106
License
MIT
Repository
github
Last release
5 months ago

FORM SCHEMA VALIDATION

Build Status Coverage Status npm npm

  1. Features
  2. Installation
  3. How to use
  4. Constructor
  5. Methods
  6. Types
  7. Example of custom validator
  8. Example of additional validator
  9. Example of Schema definition
  10. Example of schema in schema
  11. Schema keys description
  12. Custom validation messages
  13. Switch of keys validation

Features

  • sync validation
  • async validation (Promise)
  • validate object structure
  • validate object keys
  • validate required fields
  • validate optional fields
  • validate by type
  • validate by custom type
  • validate by one of type
  • validate field by custom validators
  • validate fields relations by custom validators
  • validate whole object tree by custom additional validators

Installation

$ npm install form-schema-validation --save

How to use

Schema give you posibility to validate object using schema validation. You can defined schema and use validate method to check object. Validate method allways returns errors object but if You don't have errors object is empty so You can check errors by

import Schema from 'form-schema-validation';

const schema = new Schema({
    companyName: {
        type: String
    }
});

const modelObject = {
    companyName: 'Test Company'
};

const errors = schema.validate(modelObject); // {}
const error = Object.keys(errors).length > 0; // false

Promises support

You can use validators that return Promise. If You return promis in validator then shema.validate(model) will return Promise.

import Schema from 'form-schema-validation';

const customValidator = {
    validator: (value) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(value === 'test');
            }, 1000);
        });
    },
    errorMessage: 'async test error',
}

const schema = new Schema({
    companyName: {
        type: String,
        validators:[customValidator]
    }
});

const modelObject = {
    companyName: 'Test Company'
};

const results = schema.validate(modelObject); // Promise
results.then((errors) => {
    console.log(Object.keys(errors).length > 0); // true
});

Constructor

NameTypeDescription
schemaObjectSchema will be used when you validate object
errorMessagesObjectErrors messages that will be displayed on error
validateKeysBooleanThis flag give you posibility to don't validate object keys not defined in schema

Methods

NameAttributesDescription
validatemodel: ObjectValidate Object using defined schema
setErrorkey: String, message: String, index: NumberSet error on field
setModelErrorpath: String, message: StringSet error on model tree node
getDefaultValuesGet default values for model using defined schema
getFieldname: StringGet field properties extended by parent schema instance (parentSchema)
getFieldsGet all fields schemas
oneOfTypestypes: Array of typesGive posibility to validate one of type (Static method)
pickfieldsToPick: StringGet fields from schema by keys
omitfieldsToOmit: StringGet fields from schema and omit fieldsToOmit
extendfieldsToExtend: StringExtend schema by new fields or overwrite them
extendFieldValidatorsfieldName: String, validator: { validator: Function, errorMessage: String or Function }Extend field validators
registerTypetype: SchemaTypeRegister new schema type
isValidatorRegistredvalidatorName: StringCheck model validator exists in schema
addValidatorvalidator: Function(model: Object, schema: instance of Schema)Add model validator
removeValidatorvalidator: FunctionRemove model validator

Types

NameDescription
StringSimple String type
NumberSimple Number type
ObjectSimple Object type this type give you posibility to black box
BooleanSimple Boolean type
DateThis type check value is instance of Date
ArrayThis type check value is array of any value
new SchemaThis type check value is instance of Schema and validate value by this schema
Schema.oneOfType(type1, type2, ...)This type give you posibility check one of types it will return error if value don't match all types
Schema.optionalType(type)This type will pass validation if value is null or undefined when field is not required
SchemaTypeYou can register new schema type that has name, validator, validator when field is required (requiredValidator) and getDefaultValue
OneOfTypesAboveThis type check value is array of type

Custom validator attributes

NameDescription
valueField value
fieldField properties
modelValidated object
schemaField parent schema instance

Example of custom validator

This validator will check two fields. You can validate one field on base another field.

const validateIfFieldTitleIsFilled = (minLength, message) => ({
    validator: (value, field, model, schema) => {
        if (model.title) {
            return !!value;
        }
        return true;
    },
    errorMessage: message
});

Example of additional validator

Additional validator can set error deep in the objects tree.

const fooSchema = new Schema({
    fooStart: {
        type: String,
    },
    fooEnd: {
        type: String,
    },
});
const modelSchema = new Schema({
    foo: {
        type: fooSchema,
        required: true,
    },
});
const dataModel = {
    foo: {
        fooStart: 'start',
        fooEnd: 'end',
    },
};

modelSchema.addValidator((model, schema) => {
    if(model.foo.fooStart === 'start') {
        schema.setModelError('foo.fooStart', 'my foo error message');
    }
});

modelSchema.validate(dataModel);

Example of dynamic error messages

There can be a need for error messages generated based on the validation outcome. In that case a string or array of strings can be returned from the validator function. Error messages returned from validator function have higher priority that the errorMessage property.

const MIN_AGE = 18;
const validateIfOfAge = () => ({
    validator: (value, fieldSchema, formData) => {
        const { age } = formData;
        if (age <= MIN_AGE) {
            return [`Given ${age} is lower than required age of ${MIN_AGE}`];
        }
    }
});

Example of Schema definition

If You want create new schema You must put object to constructor with information about object keys names and type of value on key.

import Schema from 'form-schema-validation';

const min = (minLength, message) => ({
    validator: (value) => {
        return value.length > minLength;
    },
    errorMessage: message
});

const schema = new Schema({
    companyName: {
        type: String,
        required: true,
        label: 'Company name',
        validators: [min(2, 'Company name should be longer then 2 chars')]
    },
    createdAt: {
        type: Schema.oneOfTypes([Date, String]),
        defaultValue: new Date(),
        label: 'When start'
    },
    workers: {
        type: Number,
        label: 'How many workers we have'
    }
});
Example of schema in schema
import Schema from 'form-schema-validation';

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    surname: {
        type: String,
        required: true
    },
    age: {
        type: Number
    }
});

const groupSchema = new Schema({
    name: {
        type: String,
        required: true,
        label: 'Group name'
    },
    createdAt: {
        type: Date,
        defaultValue: new Date(),
        label: 'Created at'
    },
    members: {
        type: [userSchema],
        label: 'Members'
    }
});
Example of use new schema type
import Schema, { SchemaType } from 'form-schema-validation';

const fooType = new SchemaType('Foo', {
    getDefaultValue() {
        return 'foo';
    },
    validator(value, key) {
        if (value.indexOf('foo') > -1 || value === '') {
            return true;
        }
        this.setError(key, 'foo error');
        return false;
    },
    requiredValidator(value, key) {
        if (value.indexOf('foo') > -1) {
            return true;
        }
        this.setError(key, 'foo required');
        return false;
    },
});

const schema = new Schema({
    foo: {
        type: fooType,
    },
    bar: {
        type: String,
    },
});

const modelWithErrors = {
    foo: 'test',
    bar: '',
};
const modelWithoutErros = {
    foo: '',
    bar: '',
};
const modelWithoutErros2 = {
    foo: 'foo',
    bar: '',
};

Schema keys description

When You defined schema You can use this keys:

KeyAllowed valuesDescription
companyName, createdAt, workers, ...any namethis key defined object key name
typeString, Number, Object, Date, Boolean, Array, instance of Schema, String ...this key tell as what type of value we should have on this key in model
requiredtrue, falsethis key tell as that field is required
defaultValueAnyYou can set default value for model
disableDefaultValueBooleanYou can disable filed default value
optionsArray of (String, Number, Object, Date, ...)If you use schema for forms You can defined options for select field
labelAny instance of StringIf you use schema for forms You can defined label for form field
validatorsarray of FunctionsYou can add custom validators for validate field for example min or max length of value.

Custom validation messages

import Schema from 'form-schema-validation';

const ErrorMessages = {
    notDefinedKey(key) { return `Key '${key}' is not defined in schema`; },
    modelIsUndefined() { return 'Validated model is undefined'; },
    validateRequired(key) { return `Field '${key}' is required`; },
    validateString(key) { return `Field '${key}' is not a String`; },
    validateNumber(key) { return `Field '${key}' is not a Number`; },
    validateObject(key) { return `Field '${key}' is not a Object`; },
    validateArray(key) { return `Field '${key}' is not a Array`; },
    validateBoolean(key) { return `Field '${key}' is not a Boolean`; },
    validateDate(key) { return `Field '${key}' is not a Date`; }
};

const groupSchema = new Schema({
    name: {
        type: String,
        required: true,
        label: 'Group name'
    },
    createdAt: {
        type: Date,
        defaultValue: new Date(),
        label: 'Created at'
    },
    members: {
        type: [userSchema],
        label: 'Members'
    }
}, ErrorMessages);

Switch of keys validation

import Schema from 'form-schema-validation';

const schema = new Schema({
    companyName: {
        type: String,
        required: true
    }
}, false, false);

const modelObject = {
    companyName: 'Test Company',
    _id: 'test1234567890',
};

const errors = schema.validate(modelObject);
console.log(Object.keys(errors).length > 0); // false
2.0.1

5 months ago

2.0.0

11 months ago

1.17.5

3 years ago

1.17.4

4 years ago

1.17.3

5 years ago

1.17.2

5 years ago

1.17.1

5 years ago

1.17.0

6 years ago

1.16.0

6 years ago

1.15.1

6 years ago

1.15.0

6 years ago

1.14.2

6 years ago

1.14.1

6 years ago

1.14.0

6 years ago

1.13.1

6 years ago

1.13.0

6 years ago

1.12.0

6 years ago

1.11.2

6 years ago

1.11.1

7 years ago

1.11.0

7 years ago

1.10.1

7 years ago

1.10.0

7 years ago

1.9.0

7 years ago

1.8.1

7 years ago

1.8.0

7 years ago

1.7.1

7 years ago

1.7.0

7 years ago

1.6.0

7 years ago

1.5.0

7 years ago

1.4.1

7 years ago

1.4.0

7 years ago

1.3.0

7 years ago

1.2.5

7 years ago

1.2.4

7 years ago

1.2.3

7 years ago

1.2.2

7 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.0

7 years ago

1.0.9

7 years ago

1.0.8

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago