实现思路:
- html中给el-form增加
:rules="rules"
- html中在el-form-item 中增加属性
prop="名称"
-
js中直接在data中定义rules:{}
1、Form 属性有(Element - The world's most popular Vue UI framework)
我们一般用到的属性有model、rules,下面是一个简单的例子
<template>
<div class="section">
<div class="ms-login">
<el-form
:model="RegisterForm"
label-width="52px"
status-icon
ref="RegisterForm"
:rules="rule"
class="register-form"
>
<h3>注册新用户</h3>
<el-form-item prop="username" label="学号">
<el-input
type="text"
v-model="RegisterForm.username"
placeholder="请输入学号"
>
</el-input>
</el-form-item>
<el-form-item prop="password" label="密码">
<el-input
type="password"
v-model="RegisterForm.password"
placeholder="请输入密码"
>
</el-input>
</el-form-item>
<el-form-item prop="Student_name" label="昵称">
<el-input
type="text"
v-model="RegisterForm.Student_name"
placeholder="请输入名字"
>
</el-input>
</el-form-item>
<el-form-item prop="Email" label="邮箱">
<el-input
type="text"
v-model="RegisterForm.Email"
placeholder="请输入邮箱"
>
</el-input>
</el-form-item>
<el-form-item>
<el-button
type="primary"
class="submitBtn"
round
@click="submit('RegisterForm')"
>
注册
</el-button>
<el-button
type="danger"
class="resetBtn"
round
@click.native.prevent="reset"
>
重置
</el-button>
<hr />
</el-form-item>
</el-form>
</div>
</div>
</template>
data中设置具体校验,代码如下:
data() {
var validateEmail = (rule, value, callback) => {
if (value === "") {
callback(new Error("请输入邮箱"));
} else {
if (
/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value) == false
) {
callback(new Error("请输入正确的邮箱"));
} else {
callback();
}
}
};
return {
RegisterForm: {
username: "",
password: "",
Student_name: "",
Email: "",
},
rule: {
username: [
{
required: true,
max: 10,
min: 10,
message: "请输入学号,长度为10位",
trigger: "blur",
},
{
pattern: /^(\w){6,20}$/,
message: "只能输入6-20个字母、数字、下划线",
},
],
password: [
{
required: true,
message: "请输入密码!",
trigger: "blur",
},
{
pattern: /^(\w){8,20}$/,
message: "只能输入8-20个字母、数字、下划线",
},
],
Student_name: [
{
required: true,
message: "请输入姓名",
trigger: "blur",
},
{
validator: function (rule, value, callback) {
if (/^[\u4E00-\u9FA5]+$/.test(value) == false) {
callback(new Error("请输入中文姓名"));
} else {
callback();
}
},
trigger: "blur",
},
],
Email: [
{
required: true,
message: "请输入邮箱",
trigger: "blur",
},
{ validator: validateEmail, trigger: "blur" },
],
},
};
},
总结:
1、我们可以设置 required:、max、min来限制长度
2、也可以用正则pattern来校验
3、也可以自己定义校验规则
校验的几种方式
validate:校验表单
this.$refs[formName].validate((valid) => {})
validateField:校验表单的某个字段
this.$refs.PassForm.validateField('checkPass');
resetFields:表单重置
this.$refs.RegisterForm.resetFields();
clearValidate:清楚表单的校验结果
this.$refs.form.clearValidate('name');
只清除表单项name的校验,不清楚表单项name的数值
与resetFields区别是:
相同点:二者都能移除表单校验
不同点:resetFields()会对整个表单进行重置,将所有的字段重置为初始值
clearValidate() 只会移除表单校验,而且可以只对部分字段进行移除校验