Form表单验证
Form 组件提供了表单验证的功能,只需要通过 rules
属性传入约定的验证规则,并将 Form-Item 的 prop
属性设置为需校验的字段名即可。
<el-form :model="temp" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="name">
<el-input v-model="temp.name"></el-input>
</el-form-item>
</el-form>
<script>
import server from 'js路径' //从外部js引入封装的请求工具
import {checkFromJs1, checkFromJs2} from '@/api/incomestruct' //从外部js引入封装的检验方法
export default {
//组件类
components: {Pagination},
//数据类
data() {
//连接服务器校验
let checkAtServer = (rule, value, callback) => {
server.fetch(this.temp.name).then(response => {
if (response.data.name) {
callback(new Error('错误!'));
} else {
callback();
}
}).catch(e => {
callback(new Error('服务检验出错!'));
})
}
//页面本地检验
let checkAtPage = (rule, value, callback) => {
if (this.temp.name === '') {
callback(new Error('不能为空!'));
} else {
callback();
}
};
return {
temp: {
name: '',
},
rules: {
name: [
{required: true, message: '不能为空!', trigger: 'blur'},
{validator: checkAtPage, trigger: 'blur'}, //页面本地校验
{validator: checkFromJs1, trigger: 'blur'}, //外部Js检验
{validator: checkAtServer, trigger: 'blur'}, //连接服务器校验
{min: 2, max: 64, message: '长度为 2-64 个字符!', trigger: 'blur'} //字符长度校验
]
}
}
},
created() {
},
methods: {
doSometing() {
//xxx操作
},
}
}
</script>