egg-async-validator
Async validate plugin for egg, sharing validator scheme between frontend and backend with Ant Design style
Install
$ npm i egg-async-validator --save
Enable plugin
// config/plugin.js
exports.validate = {
enable: true,
package: 'egg-async-validator',
};
Usage
validate(scheme, options)(values)
Define scheme, validate rules
See async-validator for more information such as custom rule
validate based on scheme, which define the shape of form fields, as simple as following
const productScheme = {
id: [{
type: 'string',
required: true,
}]
};
antd.Form
Validate in .jsx file with<Form.Item>
{getFieldDecorator('id', {
rules: productScheme.id, // share the scheme here
})(<Input />)}
</Form.Item>
Validate Request Body in chair.Controller
// app/controller/home.js
exports.index = async () => {
const error = await this.validate(productScheme, options)(this.request.body);
if (error) {
// throw manually
}
};
Tips
The package is so simple that it's easy to use as a npm module
import { validate } from 'egg-async-validator';
const errors = await validate(productScheme, options)(values);
if (errors) {
// erros maybe [{ fields: 'id', message: 'why it fail' }] or null
// throw
}
Options
The Validator provides some options for porable use in some cases
- ignoreRequire:
default false
if true, skip all required rules check for values, it's very useful for validating partial params in a patch update request
Typings
// chair.d.ts
import { ValidateType } from 'egg-async-validator';
declare module 'chair' {
export interface Context {
validate: ValidateType,
}
}
Questions & Suggestions
Please open an issue here.