Element官网:https://element.eleme.cn/#/zh-CN/component/form
操作步骤:
第一步:
命令窗口中在项目地址下:
输入npm i element-ui -S 安装elementui 依赖
第二步:
第三步:
复制上面代码到Home.vue中
下面进行我们的表单验证:
router下index.js文件配置路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'regis',
component:()=>import('@/views/RegisView.vue')
},
]
const router = new VueRouter({
routes
})
export default router
App.vue引用:
在views文件下编写RegisView.vue文件:
:model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" > type="password" v-model="ruleForm.password" autocomplete="off" > type="password" v-model="ruleForm.checkPass" autocomplete="off" > >注册 >
export default {
name: "LoginView",
data() {
var checkUser = (rule, value, callback) => {
console.log("用户名:", value);
if (value.trim() == "") {
callback(new Error("请输入用户名"));
} else if (!/^[0-9a-zA-Z_\u4e00-\u9fa5]{5,10}$/.test(value)) {
callback(new Error("用户名为5-10位中英文数字或者下划线"));
} else {
callback();
}
};
var checkEmail = (rule, value, callback) => {
console.log("邮箱:", value);
if (value.trim() == "") {
callback(new Error("邮箱不能为空"));
} else if (value.indexOf("@") == -1 || value.indexOf(".") == -1) {
callback(new Error("邮箱需要含有@和."));
} else if (value.length < 6) {
callback(new Error("邮箱需大于6位"));
} else {
callback();
}
};
var validatePass = (rule, value, callback) => {
console.log("密码:", value);
if (value.trim() == "") {
callback(new Error("请输入密码"));
} else {
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === "") {
callback(new Error("请再次输入密码"));
} else if (value !== this.ruleForm.password) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
};
return {
ruleForm: {
password: "",
username: "",
checkPass: "",
email: "",
},
rules: {
password: [{ validator: validatePass, trigger: "blur" }],
email: [{ validator: checkEmail, trigger: "blur" }],
username: [{ validator: checkUser, trigger: "blur" }],
checkPass: [{ validator: validatePass2, trigger: "blur" }],
},
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("注册成功");
} else {
console.log("注册失败");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
},
};
.myform {
width: 600px;
margin: 50px auto;
}
★☆千万别忘记使用Element一定要全局main.js里面写入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')