在平常工做中,作为一个前端码农, 常常须要与用户"交流", 用到最多的"通迅工具"莫过于表单了, 提及表单,那么就少不了验证前端
在作一件事情前, 咱们要遵循三个原则react
不解释上面三个词(自行体会),咱们继续往下走git
咱们写validator 以前, 先稍微思考一下, 顺一下思路github
好了, 大概套路就是上面两点, 再配合些许支持咱们就能实现一个简单的基于react 的验证器bash
const utils = {
testRegex: (value, regex) => value.toString().match(regex),
rules: {
required: {
message: 'The :attribute field is required',
rule: val => utils.testRegex(val, /.+/),
},
},
}复制代码
咱们先彻了一面阻止用户输入为空的墙工具
class ReactValidator {
constructor() {
this.fields = [] // 用来存放表示用户输入惟一的标识符
this.showMessage = false //默认不显示错误信息
}
}复制代码
咱们对外暴露一个守城将message,绝大部分抵御外敌的工做都由它来完成ui
class ReactValidator {
message(field, value, testString, customClass, customErrors = {}) {
// 咱们默认用户输入的都是合法的
this.fields[field] = true
let tests = testString.split('|')
let rule, options, message
for (let i = 0; i < tests.length; i++) {
// 过滤一下不存在的值
value = this.filterEmptyValue(value)
// 获取约定的规则
rule = this.getRule(tests[i])
options = this.getOptions(tests[i])
// 检测是否合法
if (!this.isValid(value, rule, options)) {
//不合法将池子里标识设为false
this.fields[field] = false
if (this.showMessage) {
// 若是用户自定义的错误的提示误就取用户的,不然取默认的
message =
customErrors[rule] ||
customErrors.default ||
this.rules[rule].message.replace(':attribute', field)
// 返回错误信息
if (
options.length > 0 &&
this.rules[rule].hasOwnProperty('messageReplace')
) {
let replaceMessage = this.rules[rule].messageReplace(
message,
options,
)
return this.createErrorEle(replaceMessage, customClass)
}
return this.createErrorEle(message, customClass)
}
}
}
}
}复制代码
以下,咱们只须要派出咱们守城将message this
render: function() {
return (
<div className="container card my-4">
<div className="card-block">
<div className="form-group">
<label>required</label>
<input className="form-control" name="required" value={this.state.require} onChange={this.setStateFromInput} />
{this.validator.message('required', this.state.required, 'required|max:12|min:6','',{
default: 'required不能为空',
min: '不能少于6个字符',
max: '不能大于12个字符'
})}
</div>
<button className="btn btn-primary" onClick={this.submitForm}>Submit</button>
</div>
</div>
);
}复制代码
以上示例代码为部分代码,完整代码见react-validatorspa