以element-ui为例,rules校验如何在行内写
时间: 2023-07-07 15:40:30 浏览: 69
对于element-ui的表单校验,我们通常是在rules属性中定义校验规则,然后在表单组件中绑定这些校验规则。如果需要在行内写校验规则,可以通过$refs属性获取表单组件的引用,然后在需要校验的地方手动调用校验方法进行校验。
以下是一个示例代码,展示了如何在行内写element-ui的表单校验规则:
```html
<el-form ref="myForm" :model="formData" label-width="80px">
<el-form-item label="姓名" prop="name">
<el-input v-model="formData.name" :class="{ 'is-invalid': $refs.myForm && $refs.myForm.fields.name && $refs.myForm.fields.name.validateMessage }"></el-input>
<span v-if="$refs.myForm && $refs.myForm.fields.name && $refs.myForm.fields.name.validateMessage" class="error-message">{{ $refs.myForm.fields.name.validateMessage }}</span>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model="formData.age" :class="{ 'is-invalid': $refs.myForm && $refs.myForm.fields.age && $refs.myForm.fields.age.validateMessage }"></el-input>
<span v-if="$refs.myForm && $refs.myForm.fields.age && $refs.myForm.fields.age.validateMessage" class="error-message">{{ $refs.myForm.fields.age.validateMessage }}</span>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
```
在上面的代码中,我们在el-input组件中使用:class绑定了一个判断条件,当该条件为真时,会为该组件添加一个is-invalid类,从而使组件变红显示错误状态。同时,我们在el-input组件下方添加了一个span元素,用于显示校验错误信息。
接着,在submitForm方法中,我们通过$refs属性获取了表单组件的引用,并手动调用了validate方法进行校验。如果校验通过,则执行表单提交操作;否则,返回错误信息。
```javascript
methods: {
submitForm() {
this.$refs.myForm.validate((valid) => {
if (valid) {
// 表单校验通过,执行提交操作
} else {
// 表单校验未通过,显示错误信息
this.$message.error('表单填写有误,请检查后重试!');
}
});
},
},
```
需要注意的是,由于是在行内写校验规则,因此我们需要手动控制错误信息的显示和隐藏。在上面的代码中,我们使用了v-if指令来根据校验结果动态显示或隐藏错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)