在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:buunguyen/koa-req-validator开源软件地址:https://github.com/buunguyen/koa-req-validator开源编程语言:JavaScript 100.0%开源软件介绍:koa-req-validatorA node-validator based request validation middleware for Koa. Unlike other libraries, this middleware provides a declarative API and enables access to the full power of node-validator. Here is a taste of it: router.post('/users', validate({
email: ['require', 'isEmail', 'Invalid email address'],
password: ['require', 'isLength(6, 32)', 'Password must be between 6 and 32 characters']
}), function *(next) {
...
}
)
// To validate properties of an object
router.post('/users', validate({
'user.name': ['require', 'Name is required'],
'user.address.state': ['require', 'State is required']
}), function *(next) {
...
}
) UsageBasic import validate from 'koa-req-validator'
router.post(path, validate(opts), ...) Options
If a field has no value, it won't be validated. To make a field required, add the special Examples import validator from 'validator'
// Add custom validator
validator['validateUserName'] = async (username, group, ctx) => {
// 1st arg (username): the value to be validate
// 2nd...2nd-to-last args (group): the extra value passed to validateUserName, i.e. "devs"
// last arg (ctx): the Koa context
return boolean | Promise<boolean>
}
validate({
// Find email from request.body and validate
'email:body': ['require', 'isEmail', 'Invalid email address'],
// Find password in all scopes, use the first non-empty value to validate
'password': ['require', 'Password is required'],
// Find birthday from request.query or request.body
'birthday:query:body': ['isDate', 'Invalid birthday'],
// Find username in all scopes
'username': ['validateUserName("devs")', 'Invalid username'],
}) Route decorators You can combine this middleware with route decorators, for example: import validate from 'koa-req-validator'
import bodyParser from 'koa-bodyparser'
@controller('/users', convert(bodyParser()))
export default class extends Ctrl {
@post('', validate(opts))
async register(ctx, next) {
...
}
} Testnpm install
npm test |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论