-
示例说明
Vue版本:vue3
组件:uviewPlus(Form 表单 | uview-plus 3.0 - 全面兼容nvue的uni-app生态框架 - uni-app UI框架)
说明:表单组建、表单验证、提交验证等;
截图:
-
示例代码
<template>
<view class="form">
<uni-section title="基本信息" type="line">
<view style="padding: 0 15px;">
<u--form labelPosition="top" :model="uForm" :rules="rules" ref="uForm">
<u-form-item label="姓名" labelWidth="60" prop="user.name" ref="item1" required>
<u--input v-model="uForm.user.name" placeholder="请输入姓名" clearable></u--input>
</u-form-item>
<u-form-item label="手机号" labelWidth="60" prop="user.phone" type="number" ref="item1" required>
<u--input v-model="uForm.user.phone" placeholder="请输入手机号" clearable maxlength="11"></u--input>
</u-form-item>
<u-form-item label="身份证" labelWidth="60" prop="user.idcard" type="idcard" ref="item1" required>
<u--input v-model="uForm.user.idcard" placeholder="请输入身份证号" clearable maxlength="18"></u--input>
</u-form-item>
<u-form-item label="家庭住址" labelWidth="100" prop="user.address" ref="item1" required>
<u--input v-model="uForm.user.address" placeholder="请输入家庭住址" clearable
maxlength="60"></u--input>
</u-form-item>
</u--form>
<view class="btn-save">
<u-button text="保存" type="primary" @click="submit"></u-button>
</view>
</view>
</uni-section>
<u-toast ref="uToastRef"></u-toast>
</view>
</template>
<script>
export default {
data() {
return {
uForm: {
user: {
name: ''
}
},
// 验证规则
rules: {
'user.name': [{
required: true,
message: '请输入姓名',
trigger: ['change', 'blur'],
},
{
// 自定义验证函数
validator: (rule, value, callback) => {
// 返回true表示校验通过,返回false表示不通过
return uni.$u.test.chinese(value);
},
message: '姓名只能输入汉字',
// 触发器可以同时用blur和change
trigger: ['change', 'blur'],
}
],
'user.phone': [{
required: true,
message: '请输入手机号',
trigger: ['blur', 'change'],
},
{
// 自定义验证函数
validator: (rule, value, callback) => {
// 返回true表示校验通过,返回false表示不通过
return uni.$u.test.mobile(value);
},
message: '手机号码不正确',
// 触发器可以同时用blur和change
trigger: ['change', 'blur'],
}
],
'user.idcard': [{
required: true,
message: '请输入身份证号',
trigger: ['change', 'blur'],
},
{
// 自定义验证函数
validator: (rule, value, callback) => {
// 返回true表示校验通过,返回false表示不通过
return uni.$u.test.idCard(value);
},
message: '身份证号不正确',
// 触发器可以同时用blur和change
trigger: ['change', 'blur'],
}
],
'user.address': {
type: 'string',
required: true,
message: '请填写家庭住址',
trigger: ['blur', 'change']
},
}
}
},
onReady() {
this.$refs.uForm.setRules(this.rules)
},
methods: {
submit() {
this.$refs.uForm.validate().then(res => {
this.$refs.uToastRef.show({
type: "success",
message: "提交成功",
})
}).catch(err => {
// uni.$u.toast('校验失败')
this.$refs.uToastRef.show({
type: "error",
message: "请检查填写内容",
})
})
}
}
}
</script>
<style lang="scss" scoped>
.form {
background-color: $white;
height: 100vh;
.btn-save {
width: 300rpx;
margin: 0 auto;
margin-top: 100rpx;
}
}
</style>