写一个 uniapp uview框架多个form表单校验字段
- 在页面中引入 uview-ui 和 uni-validate 组件:
<template>
<view>
<form>
<!-- 表单输入项 -->
</form>
<button @click="submitForm">提交</button>
</view>
</template>
<script>
import uniValidate from '@/uni_modules/uni-validate/uni-validate.js'
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import { uniPopup } from 'uview-ui'
export default {
components: {
uniPopup,
},
data() {
return {
// 表单数据
formData: {
username: '',
password: '',
},
// 表单校验规则
rules: {
username: [
{ required: true, message: '请输入用户名' },
{ pattern: /^\S+$/, message: '用户名不能包含空格' },
],
password: [
{ required: true, message: '请输入密码' },
{ pattern: /^[a-zA-Z0-9]{6,16}$/, message: '密码为 6-16 位数字或字母' },
],
},
}
},
methods: {
// 提交表单
submitForm() {
uniValidate.validateAll(this.formData, this.rules, (errors) => {
if (errors.length) {
// 显示表单错误提示
uniPopup.show({
title: '表单校验提示',
content: errors[0].message,
type: 'error',
})
} else {
// 表单校验通过,执行下一步操作
}
})
},
},
}
</script>
- 在表单项中添加校验规则:
<template>
<form>
<u-input
v-model="formData.username"
:placeholder="'请输入用户名'"
:rules="rules.username"
/>
<u-input
v-model="formData.password"
:placeholder="'请输入密码'"
type="password"
:rules="rules.password"
/>
</form>
</template>
- 在提交表单时,调用 uni-validate 的 validateAll 方法,校验表单数据:
uniValidate.validateAll(this.formData, this.rules, (errors) => {
if (errors.length) {
// 显示表单错误提示
uniPopup.show({
title: '表单校验提示',
content: errors[0].message,
type: 'error',
})
} else {
// 表单校验通过,执行下一步操作
}
})
上述代码中,validateAll 方法接受三个参数:
- formData:表单数据对象,包含所有表单项的值。
- rules:表单校验规则对象,包含所有表单项的校验规则。
- callback:校验完成后的回调函数,接受一个 errors 参数,表示校验失败的错误数组,如果数组长度为 0,则表示校验通过
原文地址: https://www.cveoy.top/t/topic/ffE8 著作权归作者所有。请勿转载和采集!