Vue Element Form 表单 验证
程序员文章站
2022-04-25 15:47:58
...
Form 表单
本示例以 Vue Element Admin 项目为基础,介绍 Form 表单
需要注意 model、rules、ref、prop 名称
:model="ruleForm"
:rules="rules"
ref="ruleForm"
prop="name"
表单验证 rules 属性约定验证规则
{ min: 5, max: 9, message: "活动名称长度在 5 到 9 个字符" }, //只能验证字符串类型
{ type: "number", message: "年龄必须为数字值" },
{ type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }
表单验证 rules 属性约定验证规则,自定义有3种方式
方式一:vue 页面中使用 pattern
rules: {
tel: [
{ required: true, message: "请输入手机号" },
{ pattern: /^(13[0-9]|14[1|4|5|6|7|8|9]|15[0|1|2|3|5|6|7|8|9]|17[2|3|5|6|7|8]|18[0-9]|19[1|8|9])\d{8}$/, message: '手机号格式不正确' }
]
}
方式二:vue 页面中使用 validator
<script>
export default {
data() {
var validatePass2 = (rule, value, callback) => {
if (value !== this.ruleForm.pass) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
};
},
return {
rules:{
age: [{ validator: checkAge }]
}
},
}
</script>
方式3:vue 页面中使用 validator + 引用 /utils/validate.js 文件
<script>
import { regPassword } from "@/utils/validate";
export default {
return {
rules:{
payPass: [
{ validator: regPassword, trigger: "blur" }
]
}
},
}
</script>
// validate.js 代码如下
export function validName(str) {
const reg = /^[a-zA-Z]+$/
return reg.test(str)
}
export var regPassword = (rule, value, callback) => {
const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/;
if (!value) {
callback(new Error('请输入支付密码'));
} else {
let check = reg.test(value);
if (!check) {
callback(new Error('支付密码为字母、数字和符号三种组合,8-20个字符'))
} else {
callback()
}
}
}
1、/src/views/demo/test-form.vue
<template>
<div class="app-container">
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="密码" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="支付密码" prop="payPass">
<el-input type="password" v-model="ruleForm.payPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<el-form-item label="手机号" prop="tel">
<el-input v-model="ruleForm.tel" auto-complete="off" placeholder="请输入手机号"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
</el-form-item>
<el-form-item label="验证码" prop="smscode" class="code">
<el-input v-model="ruleForm.smscode" placeholder="验证码"></el-input>
<el-button type="primary" :disabled="ruleForm.isSendDisabled" @click="sendCode">{{ruleForm.sendText}}</el-button>
</el-form-item>
<el-form-item label="活动区域" prop="region">
<el-select v-model="ruleForm.region" placeholder="请选择活动区域">
<el-option label="区域一" value="shanghai"></el-option>
<el-option label="区域二" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="活动时间" required>
<el-col :span="11">
<el-form-item prop="date1">
<el-date-picker
type="date"
placeholder="选择日期"
v-model="ruleForm.date1"
style="width: 100%;"
></el-date-picker>
</el-form-item>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-form-item prop="date2">
<el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
</el-form-item>
</el-col>
</el-form-item>
<el-form-item label="即时配送" prop="delivery">
<el-switch v-model="ruleForm.delivery"></el-switch>
</el-form-item>
<el-form-item label="活动性质" prop="type">
<el-checkbox-group v-model="ruleForm.type">
<el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
<el-checkbox label="地推活动" name="type"></el-checkbox>
<el-checkbox label="线下主题活动" name="type"></el-checkbox>
<el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item label="特殊资源" prop="resource">
<el-radio-group v-model="ruleForm.resource">
<el-radio label="线上品牌商赞助"></el-radio>
<el-radio label="线下场地免费"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="活动形式" prop="desc">
<el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { validName, regPassword } from "@/utils/validate";
export default {
data() {
var checkAge = (rule, value, callback) => {
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error("请输入数字值"));
} else {
if (value < 18) {
callback(new Error("必须年满18岁"));
} else {
callback();
}
}
}, 1000);
};
var validatePass2 = (rule, value, callback) => {
if (value !== this.ruleForm.pass) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
};
return {
ruleForm: {
name: "",
pass: "",
checkPass: "",
payPass: "",
age: 0,
region: "",
date1: "",
date2: "",
delivery: false,
type: [],
resource: "",
desc: "",
tel: "",
email: "",
smscode: "",
sendText: "发送验证码",
isSendDisabled: false, // 是否禁止点击发送验证码按钮
flag: true
},
rules: {
name: [
{ required: true, message: "请输入活动名称" },
{ min: 3, max: 5, message: "活动名称长度在 3 到 5 个字符" }
],
pass: [
{ required: true, message: "请输入密码" },
{ pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/, message: '密码为数字,小写字母,大写字母,特殊符号 至少包含三种,长度在8-20位' },
],
checkPass: [
{ required: true, message: "请输入确认密码", trigger: "blur" },
{ validator: validatePass2, trigger: "blur" }
],
age: [
{ required: true, message: "请输入年龄" },
{ type: "number", message: "年龄必须为数字值" },
{ validator: checkAge }
],
tel: [
{ required: true, message: "请输入手机号" },
{ pattern: /^(13[0-9]|14[1|4|5|6|7|8|9]|15[0|1|2|3|5|6|7|8|9]|17[2|3|5|6|7|8]|18[0-9]|19[1|8|9])\d{8}$/, message: '手机号格式不正确' },
],
email:[
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }
],
region: [
{ required: true, message: "请选择活动区域", trigger: "change" }
],
date1: [
{
type: "date",
required: true,
message: "请选择日期",
trigger: "change"
}
],
date2: [
{
type: "date",
required: true,
message: "请选择时间",
trigger: "change"
}
],
type: [
{
type: "array",
required: true,
message: "请至少选择一个活动性质",
trigger: "change"
}
],
resource: [
{ required: true, message: "请选择活动资源", trigger: "change" }
],
desc: [{ required: true, message: "请填写活动形式", trigger: "blur" }]
}
};
},
methods: {
sendCode() {
console.log(`Ln 181`)
let time = 10
this.ruleForm.sendText = '已发送'
this.ruleForm.isSendDisabled = true
if (this.ruleForm.flag) {
this.ruleForm.flag = false;
let timer = setInterval(() => {
time--;
this.ruleForm.sendText = time + ' 秒'
if (time === 0) {
clearInterval(timer);
this.ruleForm.sendText = '重新获取'
this.ruleForm.isSendDisabled = false
this.ruleForm.flag = true;
}
}, 1000)
}
},
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
// 生成一个随机数
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
// 生成一个随机的颜色
randomColor(min, max) {
var r = this.randomNum(min, max)
var g = this.randomNum(min, max)
var b = this.randomNum(min, max)
return 'rgb(' + r + ',' + g + ',' + b + ')'
},
checkMobile(str) {
let re = /^1\d{10}$/
if (re.test(str)) {
return true;
} else {
return false;
}
}
}
};
</script>
<style>
.code >>> .el-form-item__content {
display: flex;
align-items: center;
justify-content: space-between;
}
</style>
2、/src/utils/validate.js
/**
* Created by PanJiaChen on 16/11/18.
*/
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}
/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg = /^(([^<>()\[\]\\.,;:\aaa@qq.com"]+(\.[^<>()\[\]\\.,;:\aaa@qq.com"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}
/**
* @param {string} password
* @returns {Boolean}
*/
export function validPassword(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str === 'string' || str instanceof String) {
return true
}
return false
}
/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg)
}
export function validName(str) {
const reg = /^[a-zA-Z]+$/
return reg.test(str)
}
export var regPassword = (rule, value, callback) => {
const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/;
if (!value) {
callback(new Error('请输入支付密码'));
} else {
let check = reg.test(value);
if (!check) {
callback(new Error('支付密码为字母、数字和符号三种组合,8-20个字符'))
} else {
callback()
}
}
}
*
*
*
*
*