js 创建简单的表单同步验证器
2021-01-24 23:15
标签:phone value export date 大于 UNC log ret one js 创建简单的表单同步验证器 标签:phone value export date 大于 UNC log ret one 原文地址:https://www.cnblogs.com/ajanuw/p/13246729.htmlSyncValidate
/**
* 同步验证器
*/
export class SyncValidate {
/**
* { [key]: Validate[] }
* @param {Object} options
*/
constructor(options) {
this.options = options;
}
/**
* check({key: value})
* @param {Object} keyVal
*/
check(keyVal) {
const keys = Object.keys(keyVal);
if (!keys.length) {
throw new Error(‘至少的验证一个.‘)
}
// 只验证一个
const key = keys[0];
const val = keyVal[key];
if (!this.options.hasOwnProperty(key)) {
throw new Error(`没有设置[${key}]的验证器.`)
}
for (let v of this.options[key]) {
const errorMessage = v(val);
if (errorMessage) {
if (this.validateErrorListener && typeof this.validateErrorListener === ‘function‘) {
this.validateErrorListener(errorMessage)
}
// 验证失败立即返回
return false;
}
}
// 验证ok返回true
return true;
}
// 添加验证错误时的回调函数
addValidateErrorListener(validateErrorListener) {
this.validateErrorListener = validateErrorListener;
}
// 必填
static required(msg) {
return (input) => {
if (!input) return msg;
}
}
// 最小长度
static minLength(len, msg) {
return (input) => {
if (input.length {
if (input.length > len) return msg;
}
}
// 简单的验证手机号
static phone(msg, exp) {
const phoneExp = exp || /^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;
return (input) => {
if (!input.match(phoneExp)) {
return msg;
}
}
}
// 简单的判断相等
static eql(data, msg) {
return (input) => {
if(input !== data) return msg;
}
}
// 简单的判断相等
static equal(data, msg) {
return (input) => {
if(input != data) return msg;
}
}
}
使用
const syncValidate = new SyncValidate({
username: [
SyncValidate.required(‘用户名不能为空!‘),
SyncValidate.phone(‘请输入正确手机号!‘),
],
password: [
SyncValidate.required(‘密码不能为空!‘),
SyncValidate.minLength(8, ‘密码长度必须大于7‘),
]
});
syncValidate.addValidateErrorListener((errorMessage) => {
uni.showToast({
icon: ‘none‘,
title: errorMessage,
duration: 1500
});
})
onLogin() {
if (
!syncValidate.check({username: this.username.trim()})
||
!syncValidate.check({password: this.password.trim()})
)
{
return;
}
...
}
上一篇:[CSS]居中