2.1.3 • Published 5 years ago

lara-validator v2.1.3

Weekly downloads
3
License
MIT
Repository
gitlab
Last release
5 years ago

LaraValidator

semantic-lab/lara-validator is a validator based on Laravel rules. With our validator, it's simple to check the object or request data by simple rules setting.

With also exactly same rule configurations, we also create a Laravel artisan command expansion "semantic-lab/lara-validator" for generate FormRequest with validation rules more easily.

Usage

via npm install

npm install lara-validator --save

ES6

import { LaraValidator } from 'lara-validator';

const registerFormRules = {
    name: 'required|string|min:4',
    email: 'required|email',
    password: 'required|string|min:6|regex:/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?]).*$/i|confirmed',
    phone: 'required|regex:/^(09)[0-9]{8}$/gi|bail',
    gender: 'nullable|numeric|in:0,1,2',
    address: 'present|string',
};

const registerForm = {
    name: undefined,
    email: 'familywithloveg@gmail.com',
    password: '!aA00Bb%',
    password_confirmation: '!aA00Bb%',
    phone: '0911000001',
    gender: 1,
    address: 'Taipei, Taiwan',
};

const validator = new LaraValidator(registerFormRules, registerForm);

const pass = validator.valid();

if (!pass) {
    const errorMessages = validator.errorMessage;
    // ... 
}

Release Note

There are two changed in version 2.0. First, we make the errorMessage of field in array more accurately.

const rules = {
    users: [{
        name: 'required|string',
        email: 'required|email',
    }],
};

const invalidData = [
    { name: 'Albert Lin', email: 'familywithloveg@gmail.com' },
    { name: 'Rex Chien', email: undefined },
];

const validator = new LaraValidator(rules, invalidData);

validator.valid();

// errorMessage in version 1.0 & 1.1:
// { 'users.*.email': [...] }

// errorMessage in version 2.0:
// { 'users.1.email': [...] }

Second, the input of customize validator changed from object into RuleMeta instance, check Expansion Customize Validators for more details.

Rule Config

Our rule config is based on Laravel validator setting, there are some little different to make it more flexible.

Simple Setting

If the fields to valid are all in one layer, it's pretty simple to set the rule config.

Default Error Message

For default error message, we only needs to set the rules as field's value.

const rules = {
    name: 'required|string|min:4',
    email: 'required|email',
    password: 'required|string|min:6|regex:/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?]).*$/i|confirmed',
    phone: 'required|regex:/^(09)[0-9]{8}$/gi|bail',
    gender: 'nullable|numeric|in:0,1,2',
    address: 'present|string',
};

Custom Error Message

In some case we needs to set our custom error message for specific fields, in this case, we will add all rules as key under the {field}.rules object. To use default error message, can set value of rules as null.

const rules = {
    name: {
        rules: {
            'required': 'The field "name" is required.',
            'string': 'Type of The field "name" should be String.',
            'min:4': 'The field "name" should not be less than 4 characters.',
        },
    },
    email: 'required|email',
    password: 'required|string|min:6|regex:/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?]).*$/i|confirmed',
    phone: 'required|regex:/^(09)[0-9]{8}$/gi|bail',
    gender: 'nullable|numeric|in:0,1,2',
    address: 'present|string',
};

If the field "name" has only 2 characters, the return error message will be custom error message: "The field "name" should not be less than 4 characters.".

Complex Setting

There are more example show as below for the data with more complex structure, like array or nested object.

Nested Rule Setting

To set the nested field, just set as nested object.

const rules = {
    id: 'required|string',
    token: 'required|string',
    group: {
        isPrivate: 'boolean',
        groupName: 'required|string',
        startDate: 'present|date',
        frequency: 'present|in:1,30,90',
        endDate: 'present|date',
    },
};

As the field "group", there are several more sub-fields have to be validated, we will set all sub-fields under it.

Array Rules Setting

For valid all sub-fields in an array field, set an example in the array value.

const rules = {
    users: [
        {
            name: 'required|string|min:4',
            email: 'required|email',
            password: 'required|string|min:6|regex:/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*?]).*$/i|confirmed',
            phone: 'required|regex:/^(09)[0-9]{8}$/gi|bail',
            gender: 'nullable|numeric|in:0,1,2',
            address: 'present|string',
        }
    ],
};

Including to the example, it is a rule of api which register several user at once, because all the user have same fields should be validated, we only need set once as example in the array value of field "users".

Rules

There are all validation rules of Laravel 5.8. The rule in strikethrough means it is not supporting in this version.

AcceptedDistinctNullable
Active URLE-MailNumeric
After (Date)Exists (Database)Present
After Or Equal (Date)FileRegular Expression
AlphaFilledRequired
Alpha DashGreater ThanRequired If
Alpha NumericGreater Than Or EqualRequired Unless
ArrayImage (File)Required With
BailInRequired With All
Before (Date)In ArrayRequired Without
Before Or Equal (Date)IntegerRequired Without All
BetweenIP AddressSame
BooleanJSONSize
ConfirmedLess ThanStarts With
DateLess Than Or EqualString
Date EqualsMaxSometimes
Date FormatMIME TypesTimezone
DifferentMIME Type By File ExtensionUnique (Database)
DigitsMinURL
Digits BetweenNot InUUID
Dimensions (Image Files)Not Regex

Advanced

Expansion Customize Validators

To adding customize rules or replacing the logic of original one, only needs to passing an object with customize rules argument when create a new LaraValidator instance or invoke LaraValidator function "setExpansionValidators".

import { LaraValidator } from 'lara-validator';

const customizeValidators = {
    accepted(ruleMeta) {
        // ...
    },
    phone(ruleMeta) {
        // ...
    },
};

const rules = {};
const data = {};
const validator = new LaraValidator(rules, data, customizeValidators);
const pass = validator.valid();

In the example above, with given customize validators, first, the original validator "accepted" will be replace to customize version; second, new validator "phone" will add into the validator list.

The parameter "ruleMeta" is an instance of RuleMeta, the properties and functions of RuleMeta show as below:

propertytypedescription
dataObjectthe data passing into LaraValidator
fieldParentPathArrayall ancestors field name (note, if ancestor is an array, the field name will be '*')
fieldNameStringcurrent validation field name
fieldPathArrayall ancestors field name and current validation field name
ruleStringcurrent validation rule name with option part
ruleNameStringcurrent validation rule name without option
ruleOptionsStringcurrent validation rule option part
isNullableBooleanthe field rules include 'nullable'
presentOnlyBooleanthe field rules include 'present'
parentValuesArrayall ancestors field value information
parentValues.*.pathArraythe path of ancestor field (note, the '*' will be replaced into index of array)
parentValues.*.value*the value of ancestor field
functionleveldescription
isInitcheck "fieldName" & "ruleName" has be set
setFieldPathset/update "fieldParentPath", "fieldName" and "fieldPath"
resetRulereset "rule", "ruleName", "ruleOptions", "isNullable" and "presentOnly" to default value (null and false)
setRuleset/update "rule", "ruleName", "ruleOptions", "isNullable" and "presentOnly"
setParentValuesset parentValues with given argument
needToValidatecheck the given value has to be validated
getValuesByPathsstaticget the information (path and value) of given path(array)
pathTypestaticget the type('ONE_COMPARE_WITH_ONE', 'ONE_COMPARE_WITH_MULTI', 'MULTI_COMPARE_WITH_ONE' and 'MULTI_COMPARE_WITH_MULTI') between two given path(string)

Customize Default Error Message of Rule

Sometimes you may wish to customize error message of rules to your own or form i18n, to make the rule config set in simple mode, you just need pass an object of rule's error message as fourth argument in LaraValidator instance or of course, invoke LaraValidator function "setCustomRulesMessage".

import { LaraValidator } from 'lara-validator';

const errorMessage_zh_tc = {
    accepted: '此欄位只能允許以下可以表達「是」或「允許」的值("yes", "on", "true", "1", 1, true)',
    required: '此欄位為必要欄位,不可為空值',
    // ...
};

const rules = {
    name: 'required'
};
const data = {};
const validator = new LaraValidator(rules, data, undefined, errorMessage_zh_tc);
const pass = validator.valid();

In the example above, we pass an object of error message in Traditional Chinese. After validation, we can get "required" rule's error message "此欄位為必要欄位,不可為空值" in validator.errorMessage.

References

2.1.3

5 years ago

2.1.2

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago