vue---表单校验-rules外部引入自定义校验(validator)
以邮箱校验为例:1.【validate.js】中自定义邮箱验证规则/* 电子邮箱校验 */export function validateEmail(str) {const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/return reg.test(str)}2.在<...
·
以邮箱校验为例:
1.【validate.js】中自定义邮箱验证规则
/* 电子邮箱校验 */
export function validateEmail(str) {
const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
return reg.test(str)
}
2.在<script>标签中引入外部邮箱验证规则【import { validateEmail } from "../assets/js/validate.js"】
const:定义一个规则常量,常量名可变,【= (rule, value, callback) => {}】为固定格式,【value】 为验证的字段值
<script>
import axios from "axios";
// 引入了外部的验证规则
import { validateEmail } from "../assets/js/validate.js";
// 判断邮箱是否正确
const validatorEmail = (rule, value, callback) => {
if (!value) {
return callback(new Error("邮箱不能为空"));
} else {
if (validateEmail(value)) {
callback();
} else {
return callback(new Error('邮箱格式不正确'))
}
}
};
export default {
name: "login",
data() {
return {
activeName: "login",
checked: false,
user: {
username: "",
password: ""
},
// 通过 formRules 属性传入约定的验证规则
formRules: {
username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
password: [
{ required: true, message: "密码不能为空", trigger: "blur" },
{ type: 'string', min: 6, message: '密码不能小于6位', trigger: 'blur' }
],
email: [{ required: true, validator: validatorEmail, trigger: "blur" }]
},
};
},
}
更多推荐
已为社区贡献45条内容
所有评论(0)