Form validation for uni-app uni-forms components

foreword

  • When using uni-app development recently, when using the enhanced form, the difference between the process of using the form verification and the PC side
  • The uni-app document says that if you want to use custom form validation, you need to remove the form: rules="rules" and use ref binding
  • But in the end I use validateFunction a custom validation rule, which will be triggered using the above two methods,
  • Personally, I think the official documents are the main ones. If :rules="rules" fails and causes errors, the loss outweighs the gain

Documentation

 

<template>
	<view>
		<uni-forms ref="form" :rules="rules" :modelValue="formData">
			<uni-forms-item label="兴趣爱好" required name="hobby">
				<uni-data-checkbox v-model="formData.hobby" multiple :localdata="hobbys" />
			</uni-forms-item>
		</uni-forms>
		<button class="button" @click="submit">校验表单</button>
	</view>
</template>
<script>
export default {
	data() {
		return {
			formData:{
				
			},
			rules: {
				hobby: {
					rules: [{
						required: true,
						errorMessage: '请选择兴趣',
					},{
						validateFunction:function(rule,value,data,callback){
							if (value.length < 2) {
								callback('请至少勾选两个兴趣爱好')
							}
							return true
						}
					}]
				}
			}
		}
	},
    // 注意form表单是写了:rules="rules"的
    // 这2种方式都会触发自定义表单验证
	// onReady() {
		// 需要在onReady中设置规则
	    // this.$refs.form.setRules(this.rules)
	// },
	methods: {
		submit(form) {
			this.$refs.form.validate().then(res=>{
				console.log('表单数据信息:', res);
			}).catch(err =>{
				console.log('表单错误信息:', err);
			})
		}
	}
}
</script>

Summarize:

After this process, I believe you have a preliminary deep impression on the form validation of the uni-app uni-forms component, but the situation we encounter in actual development is definitely different, so we need to understand its principle , ever-changing remains the same. Come on, hit the workers!

Please point out any deficiencies, thank you -- Fengguowuhen

Guess you like

Origin blog.csdn.net/weixin_53579656/article/details/131316092