使用 Joi 表单验证

安装 Joi 库:

 npm i [email protected]

基本使用:

import Joi from 'joi-browser';

schema = {
    username: Joi.string().required().label('Username'),
    password: Joi.string().required().label('Password')
  };

const data = {username: 'tom', password: 12345};
// data 是要验证的数据对象,schema 是验证规则
const result = Joi.validate(data, schema);

如果验证不通过,错误信息在 result.error.details 中,如果验证通过result.error 值为 null

更多用法见文档:https://hapi.dev/family/joi/?v=15.1.0




Joi 的基本数据类型:

any
array
boolean
binary
date 
func
number
object
string 
symbol
alternatives

你可能感兴趣的:(使用 Joi 表单验证)