lara-validator v2.1.3
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.
Accepted | Distinct | Nullable |
Numeric | ||
After (Date) | Present | |
After Or Equal (Date) | File | Regular Expression |
Alpha | Filled | Required |
Alpha Dash | Greater Than | Required If |
Alpha Numeric | Greater Than Or Equal | Required Unless |
Array | Image (File) | Required With |
Bail | In | Required With All |
Before (Date) | In Array | Required Without |
Before Or Equal (Date) | Integer | Required Without All |
Between | IP Address | Same |
Boolean | Size | |
Confirmed | Less Than | Starts With |
Date | Less Than Or Equal | String |
Date Equals | Max | |
MIME Types | ||
Different | MIME Type By File Extension | |
Digits | Min | URL |
Digits Between | Not In | UUID |
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:
property | type | description |
---|---|---|
data | Object | the data passing into LaraValidator |
fieldParentPath | Array | all ancestors field name (note, if ancestor is an array, the field name will be '*') |
fieldName | String | current validation field name |
fieldPath | Array | all ancestors field name and current validation field name |
rule | String | current validation rule name with option part |
ruleName | String | current validation rule name without option |
ruleOptions | String | current validation rule option part |
isNullable | Boolean | the field rules include 'nullable' |
presentOnly | Boolean | the field rules include 'present' |
parentValues | Array | all ancestors field value information |
parentValues.*.path | Array | the path of ancestor field (note, the '*' will be replaced into index of array) |
parentValues.*.value | * | the value of ancestor field |
function | level | description |
---|---|---|
isInit | check "fieldName" & "ruleName" has be set | |
setFieldPath | set/update "fieldParentPath", "fieldName" and "fieldPath" | |
resetRule | reset "rule", "ruleName", "ruleOptions", "isNullable" and "presentOnly" to default value (null and false) | |
setRule | set/update "rule", "ruleName", "ruleOptions", "isNullable" and "presentOnly" | |
setParentValues | set parentValues with given argument | |
needToValidate | check the given value has to be validated | |
getValuesByPaths | static | get the information (path and value) of given path(array) |
pathType | static | get 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.