uniapp 表单校验

需求如下: 同时校验手机号和邮箱
uniapp 表单校验_第1张图片
实现代码:

<template>
	<view class="container">
		<uni-section title="自定义校验规则" type="line">
			<view class="example">
				<!-- 自定义表单校验 -->
				<uni-forms ref="customForm" :rules="customRules" labelWidth="80px" :modelValue="customFormData">
					<uni-forms-item label="用户名" required name="name">
						<uni-easyinput v-model="customFormData.name" placeholder="请输入手机号或者邮箱" />
					</uni-forms-item>
					<uni-forms-item label="年龄" required name="age">
						<uni-easyinput v-model="customFormData.age" placeholder="请输入年龄" />
					</uni-forms-item>
					
				</uni-forms>
				<button type="primary" @click="submit('customForm')">提交</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 自定义表单数据
				customFormData: {
					name: '',
					age: '',
					hobby: []
				},
				// 自定义表单校验规则
				customRules: {
					name: {
						rules: [
							{
							required: true,
							errorMessage: '用户名不能为空'
						    },
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.indexOf('.com')>-1||value.indexOf('@')>-1) {
										let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
										if (!reg.test(value)) {
											callback('请输入正确的邮箱')
										}
									}else{
										let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[1457]|19[0-9]|16[0-9])[0-9]{8}$/;
										if (!reg.test(value)) {
											callback('请输入正确的手机号')
										}
									}
									return true
								}
							}
							
						]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}]
					},

				},
				}
		},
		onReady() {
			// 设置自定义表单校验规则,必须在节点渲染完毕后执行
			this.$refs.customForm.setRules(this.customRules)
		},
		methods: {
			submit(ref) {
				console.log(this.baseFormData);
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

forms组件

你可能感兴趣的:(uniapp,uni-app,javascript,前端)