本文介绍了一个基于 JavaScript 实现的类 Laravel 表单验证库。该库支持安装使用,提供 required、email 等内置规则,并允许通过匿名函数自定义扩展规则。通过配置 messages 参数,可实现不同粒度的错误提示,帮助开发者在前端快速构建健壮的表单校验逻辑。
介绍
Laravel 框架在前端表单验证方面提供了便捷的机制,为了在前端项目中实现类似的验证体验,开发者希望有对应的解决方案。
相关代码已托管在 Git 仓库中,欢迎 Star 支持。
期望该表单验证库具备以下功能特性。
let validator = new Validation(this.registerForm, {
telephone: "required|telephone",
captcha: "required|length:5",
}, {
telephone: {
required: "手机号不能为空",
telephone: "手机号格式不正确",
},
captcha: "验证码不正确"
})
try {
validator.validate()
} catch(e) {
uni.showToast({
icon: 'error',
title: e.message
})
}构造函数的第三个参数 messages 并非必填,默认情况下会返回英文提示信息。该参数支持不同粒度的错误信息配置:若传入对象,则当对应规则校验失败时,使用对象中定义的特定错误信息;若传入字符串,则无论哪条规则未通过,均统一使用该字符串作为错误提示。
库中内置了多种常用验证规则,若现有规则无法满足需求,还支持用户自行扩展。
基于上述需求,开发了该验证库 @church1117/form-validation。
安装
npm install @church1117/form-validation使用
import Validation from "@church1117/form-validation"
let data = {
name: "church",
mobile: "18565919379",
age: 19,
gender: '2',
password: "123456",
captcha: "12345",
idcard: '42052919910727452X',
email: "xxx@qq.com",
test: "ttt",
birthday: '1993/11/17',
}
let rules = {
name: "required|between:6,255",
mobile: "required|telephone",
age: "numeric|between:8,60",
gender: "numeric|range:" + gender.join(','),
password: "required|min:6|password",
captcha: "required|length:5",
idcard: "required|idcard",
email: "email",
// test: "required|testRule"
birthday: "datetime"
}
let messages = {
name: {
required: "名字不能为空",
between: "名称长度必须在6~255之间",
},
mobile: "不正确的手机格式",
age: {
numeric: "年龄不是一个有效的数值",
between: "年龄必须在18-60岁之间"
},
password: {
required: "密码不能为空",
min: "密码长度不能小于6位",
regex: "密码只能由数字、大小写字母构成",
},
captcha: "验证码不正确",
idcard: {
required: "身份证不能为空",
idcard: "身份证格式不正确",
},
test: {
required: "测试字段不能为空",
testRule: "该字段的值必须为test"
}
}
let validation = new Validation(data, rules, messages);- messages 参数可用于定义不同粒度的错误信息。若配置为字符串,则该字段的所有验证规则均使用此统一提示;若配置为对象,则仅在使用对应规则校验失败时,返回对象中定义的具体错误信息。
内置规则
- required
- telephone
- min
- max
- between
- idcard
- range
- password
- numeric
- length
- datetime
自定义规则
匿名函数参数(value, field, ...params)
- value
- field
- ...params
Validation.register('testRule', function(value, field) {
if (typeof value != 'undefined' && value != 'test') {
throw new Error(`${field} must equal test`)
}
});测试
npm test以上就是使用JS手写一个类似 Laravel 验证器的表单验证器的详细内容,更多关于JS Laravel表单验证器的资料请关注本站其它相关文章!