@abalmus/validator 中文文档教程
Validation Processor
Description
ValidationProcessor - 低级异步验证引擎。 专为测试数据而设计,基于验证规则。 可以使用自定义验证器轻松扩展。 与任何现代框架或 VanillaJS 兼容。
Installation
// NPM
npm install @abalmus/validator
// YARN
yarn add @abalmus/validator
Usage
Validation processor initialization
import { ValidationProcessor } from '@abalmus/validator';
const constrains = {
rules: {
firstName: {
minlength: 10
}
},
messages: {
firstName: {
minlength: 'First name needs to be not less than 10 characters'
}
}
};
/*
* ValidateProcessor constructor
* params: ( constrains, [options] )
* returns: instance of the validation processor
*/
const validationProcessor = new ValidationProcessor(constrains);
/*
* validate
* params: ( fieldName, value, [options] )
* returns: undefined
*/
validationProcessor.validate('firstName', 'myname');
Getting validation errors
从验证处理器获取错误的最简单方法是使用 ErrorPopulator。
import { ErrorsPopulator } from '@abalmus/validator';
/*
* ErrorPopulator constructor
* params: ( validationProcessorInstance, [options] )
* returns: errors populator instance
*/
const errors = new ErrorsPopulator(validationProcessor);
/*
* getByField emthod
* params: ( fieldName, [options] )
* returns: Promise
*/
errors.getByField('firstName').then((errors) => console.log(errors));
// [{minlength: "First name needs to be not less than 10 characters"}]
Validators
Build in Validators
const constrains = {
rules: {
firstName: {
minLength: 4,
maxLength: 10,
required: true,
equal: 'John',
pattern: /^[a-zA-Z ]+$/
}
},
messages: {
firstName: {
minLength: 'Please insert minimum 4 characters',
maxLength: 'Please insert maximum 10 characters',
required: 'Please insert first name',
equal: 'Please insert correct name',
pattern: 'Only letters allowed'
}
}
}
"maxLength" and "minLength"
minLength
和 maxLength
这些验证器中的每一个都将任何值转换为字符串并检查长度属性。
"equal" validator
简单的相等性检查,比较值和类型。
"pattern" validator
JavaScript Regexp 测试方法执行搜索以查找 pattern
属性中提供的正则表达式与指定字符串之间的匹配项。
"async" validator
为服务器端验证创建的异步验证器。 示例电子邮件地址存在,当您进行 ajax 调用以检查电子邮件是否存在时。
const constrains = {
rules: {
email: {
async: {
url: 'api/email/exist',
// ...other fetch API options
}
}
},
messages: {
email: {
async: 'Email already exists.'
}
}
}
默认服务器端响应格式:
{
status: 'ERROR', // ['SUCCESS', 'ERROR', 'INFO']
message: 'Server message goes here' // will be rendered below the field
}
Custom Validators
这个库最重要的部分是自定义验证器的创建。 这是扩展验证处理器的强大机制。 要注册验证器,请调用 validator.registerValidator
方法。
import {
validator,
ValidationProcessor
} from '@abalmus/validator';
validator.registerValidator('moreOrEqual', (value, ruleValue) => {
return (Number(value) >= Number(ruleValue));
});
现在我们可以在约束中使用 moreOrEqual
验证器。
const constrains = {
rules: {
age: {
moreOrEqual: 16
}
},
messages: {
age: {
moreOrEqual: 'You needs to be at least 16 years old'
}
}
}
const validationProcessor = new ValidationProcessor(constrains);
validationProcessor.validate('age', 18); // Valid!
"dependsOn" rule wrapper
一种更强大和有用的机制是 dependsOn
规则包装器。 此包装器允许应用验证规则取决于其他值。
德国的示例电话模式与美国不同。
const constrains = {
rules: {
phoneNumber: {
dependsOn: {
country: {
US: {
rules: {
pattern: // US phone number regex
minLength: 10
}
},
DE: {
rules: {
pattern: // DE phone number regex
minLength: 8
}
}
}
}
}
}
};
如您所见,有嵌套的 dependsOn 包装器和规则。 根据国家价值自动应用国家内部的规则。
How to use:
选项 1:在初始化阶段将 dependsOnValues
传递给 ValidationProcessor 配置
const validationProcessor = new ValidationProcessor(constrains, {
dependsOnValues: {
country: 'US'
}
});
validationProcessor.validate('phoneNumber', '123456787') // not valid
选项 2:将 dependsOnValues
作为 validate
方法的第三个参数传递
const validationProcessor = new ValidationProcessor(constrains);
validationProcessor.validate('phoneNumber', '123456787', { country: 'US' }) // not valid
Validation Processor
Description
ValidationProcessor - low-level asynchronous validation engine. Designed for testing data, based on validation rules. Can be easily extended with custom validators. Compatible with any modern frameworks or VanillaJS.
Installation
// NPM
npm install @abalmus/validator
// YARN
yarn add @abalmus/validator
Usage
Validation processor initialization
import { ValidationProcessor } from '@abalmus/validator';
const constrains = {
rules: {
firstName: {
minlength: 10
}
},
messages: {
firstName: {
minlength: 'First name needs to be not less than 10 characters'
}
}
};
/*
* ValidateProcessor constructor
* params: ( constrains, [options] )
* returns: instance of the validation processor
*/
const validationProcessor = new ValidationProcessor(constrains);
/*
* validate
* params: ( fieldName, value, [options] )
* returns: undefined
*/
validationProcessor.validate('firstName', 'myname');
Getting validation errors
The easiest way of getting errors from validation processor is using ErrorPopulator.
import { ErrorsPopulator } from '@abalmus/validator';
/*
* ErrorPopulator constructor
* params: ( validationProcessorInstance, [options] )
* returns: errors populator instance
*/
const errors = new ErrorsPopulator(validationProcessor);
/*
* getByField emthod
* params: ( fieldName, [options] )
* returns: Promise
*/
errors.getByField('firstName').then((errors) => console.log(errors));
// [{minlength: "First name needs to be not less than 10 characters"}]
Validators
Build in Validators
const constrains = {
rules: {
firstName: {
minLength: 4,
maxLength: 10,
required: true,
equal: 'John',
pattern: /^[a-zA-Z ]+$/
}
},
messages: {
firstName: {
minLength: 'Please insert minimum 4 characters',
maxLength: 'Please insert maximum 10 characters',
required: 'Please insert first name',
equal: 'Please insert correct name',
pattern: 'Only letters allowed'
}
}
}
"maxLength" and "minLength"
minLength
and maxLength
each of these validators convert any value to a string and checks length property.
"equal" validator
Simple equality check, comparing value and type.
"pattern" validator
JavaScript Regexp test method executes a search for a match between a regular expression provided in pattern
property and a specified string.
"async" validator
Async validator created for server side validations. The example email address existence, when you make an ajax call to check if email exists or not.
const constrains = {
rules: {
email: {
async: {
url: 'api/email/exist',
// ...other fetch API options
}
}
},
messages: {
email: {
async: 'Email already exists.'
}
}
}
Default server side response format:
{
status: 'ERROR', // ['SUCCESS', 'ERROR', 'INFO']
message: 'Server message goes here' // will be rendered below the field
}
Custom Validators
The most important part of this library is a creation of custom validators. This is powerful mechanism of extending validation processor. To register validator lets call validator.registerValidator
method.
import {
validator,
ValidationProcessor
} from '@abalmus/validator';
validator.registerValidator('moreOrEqual', (value, ruleValue) => {
return (Number(value) >= Number(ruleValue));
});
Now we can use moreOrEqual
validator inside constrains.
const constrains = {
rules: {
age: {
moreOrEqual: 16
}
},
messages: {
age: {
moreOrEqual: 'You needs to be at least 16 years old'
}
}
}
const validationProcessor = new ValidationProcessor(constrains);
validationProcessor.validate('age', 18); // Valid!
"dependsOn" rule wrapper
One more powerful and useful mechanism is dependsOn
rules wrapper. This wrapper allows to apply validation rules depends on other values.
The example phone pattern for Germany is different than in the United States.
const constrains = {
rules: {
phoneNumber: {
dependsOn: {
country: {
US: {
rules: {
pattern: // US phone number regex
minLength: 10
}
},
DE: {
rules: {
pattern: // DE phone number regex
minLength: 8
}
}
}
}
}
}
};
As you can see there are nested dependsOn wrapper and rules. The rules inside the country automatically applied based on country value.
How to use:
Option 1: Passing dependsOnValues
to ValidationProcessor config on initialization phase
const validationProcessor = new ValidationProcessor(constrains, {
dependsOnValues: {
country: 'US'
}
});
validationProcessor.validate('phoneNumber', '123456787') // not valid
Option 2: Passing dependsOnValues
as a third parameter of the validate
method
const validationProcessor = new ValidationProcessor(constrains);
validationProcessor.validate('phoneNumber', '123456787', { country: 'US' }) // not valid