安装
yarn add ajv -S
例子
var Ajv = require('ajv')
// or ESM/TypeScript import
const schema = {
type: 'string',
minLength: 10,
}
var ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema)
var valid = validate('Jokcy')
console.log(valid)
if (!valid) console.log(validate.errors)
表单验证和自定义错误
安装ajv-errors
yarn add ajv-errors -S
使用
import Ajv from 'ajv';
var ajv = new Ajv({ allErrors: true, jsonPointers: true });
require('ajv-errors')(ajv /*, {singleError: true} */);
data() {
return {
nickname: '',
mobile: '',
password: '',
vcode: '',
avatar: '',
gender: 0
};
},
computed: {},
methods: {
bindReg() {
var that = this;
var schema = {
type: 'object',
properties: {
nickname: {
type: ['number', 'string'],
minLength: 1,
errorMessage: {
type: '请输入昵称',
minLength: '请输入昵称'
}
},
mobile: {
type: ['number', 'string'],
minLength: 11,
errorMessage: {
type: '请输入手机号',
minLength: '请输入11位的手机号码'
}
},
password: {
type: ['number', 'string'],
minLength: 6,
errorMessage: {
type: '请输入密码',
minLength: '请输入最少6位密码'
}
},
vcode: {
type: ['number', 'string'],
minLength: 4,
errorMessage: {
type: '请输入验证码',
minLength: '请输入验证码'
}
},
avatar: {
type: ['number', 'string'],
minLength: 1,
errorMessage: {
type: '请上传头像',
minLength: '请上传头像'
}
}
}
};
var validate = ajv.compile(schema);
console.log(this.mobile);
var valid = validate({
nickname: that.nickname,
mobile: that.mobile,
password: that.password,
vcode: that.vcode,
avatar: that.avatar,
gender: that.gender
});
if (!valid) {
localize.zh(validate.errors);
console.log(validate.errors);
uni.showToast({
title: validate.errors[0]['message'],
icon: 'none'
});
} else {
that.$minApi
.reg({
nickname: that.nickname,
mobile: that.mobile,
password: that.password,
vcode: that.vcode,
avatar: that.avatar,
gender: that.gender
})
.then(res => {
console.log(res);
if (res.code == 200) {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
}
});
}
},
}