uniapp form表单校验

公司的一个老项目,又要重新上架,uniapp一套代码,打包生成iOS端发布到App Store,安卓端发布到腾讯应用宝、OPPO、小米、华为、vivo,安卓各大应用市场上架要求不一样,可真麻烦啊

光一个表单校验,就整了半天,以前用的都是element-ui的,现成的组件,这有换成uni-form的,记录一下怎么用的,还用到了uni-data-picker选择器(不过只能两级,得搞个方法封装一下能多级

包括:必填校验,手机号校验,身份证号校验,邮箱校验

 

带required的就是有校验
name要对应model里的值,要统一

// 限制只能输入数字
{
    format: 'number',
    errorMessage: '企业规模请输入数字'
}

// 手机号校验
{
    pattern: /^1[0-9][0-9]\d{8}$/,
    errorMessage: '请输入正确的手机号码'
}

// 身份证号校验
{
    pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
    errorMessage: '请输入正确的身份证号码'
}

// 邮箱校验
{
    format: 'email',
    errorMessage: '请输入正确的邮箱'
}

demo代码

<template>
	<view class="curr_main">
		<view>
			<uni-forms :modelValue="formData" ref="uniForm" :rules="uniRules">
				<uni-forms-item class="cu-form-group" label="企业名称:" name="enterpriseName" required>
					<input type="text" v-model="formData.enterpriseName" placeholder="请输入企业名称" />
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="企业简称:" name="enterpriseShortName" required>
					<input type="text" v-model="formData.enterpriseShortName" placeholder="请输入企业简称" />
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="企业规模:" name="enterpriseScale" required>
					<input v-model="formData.enterpriseScale" placeholder="请输入企业规模(人)" />
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="联系电话:" name="phone" required>
					<input type="text" v-model="formData.phone" placeholder="请输入联系电话" />
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="企业所在城市:" name="districtId" required>
					<uni-data-picker placeholder="请选择企业所在城市" popup-title="请选择企业所在城市" :localdata="cityTree" v-model="formData.districtId" @change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened" @popupclosed="onpopupclosed">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="详细地址:" name="phone">
					<textarea maxlength="-1" @input="textareaBInput" v-model="formData.address" placeholder="请输入详细地址"></textarea>
				</uni-forms-item>
				<uni-forms-item class="cu-form-group margin-top" label="姓名:" name="legalName" required>
					<input type="text" v-model="formData.legalName" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item class="cu-form-group" label="身份证号码:" name="legalPassNumber" required>
					<input type="text" v-model="formData.legalPassNumber" placeholder="请输入身份证号" />
				</uni-forms-item>
                <uni-forms-item class="cu-form-group" label="邮箱:" name="email" required>
					<input type="text" v-model="formData.email" placeholder="请输入邮箱" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="flex justify-between padding-sm bg-fff">
			<button class="cu-btn round button-primary width-48" style="width:100%" @click="submit()">提交</button>
		</view>
	</view>
</template>
<script>
	export default{
		data(){
			return{
				pickerData: '',
				formData: {
					districtId: '',
					enterpriseName: '',
					enterpriseShortName: '',
					enterpriseCertificateType: '',
					certificateCode: '',
					enterpriseScale: '',
					phone: '',
					address: '',
					legalName: '',
					legalPassType: '',
					legalPassNumber: '',
					id: uni.getStorageSync('userId'),
                    email: ''
				},
				cityTree: [],
				uniRules: {
					enterpriseName: {
						rules: [{
							required: true,
							errorMessage: '请输入企业名称',
						}]
					},
					enterpriseShortName: {
						rules: [{
							required: true,
							errorMessage: '请输入企业简称',
						}]
					},
					districtId: {
						rules: [{
							required: true,
							errorMessage: '请选择企业所在城市',
						}]
					},
					enterpriseScale: {
						rules: [
							{
								required: true,
								errorMessage: '请输入企业规模'
							},
							{
								format: 'number',
								errorMessage: '企业规模请输入数字'
							}
						]
					},
					phone: {
						rules: [
							{
								required: true,
								errorMessage: '请输入联系电话',
							},
							{
								pattern: /^1[0-9][0-9]\d{8}$/,
                                errorMessage: '请输入正确的手机号码'
							}
						]
					},
					legalName: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					legalPassNumber: {
						rules: [
                            {
                                required: true,
                                errorMessage: '请输入身份证号码',
                            },
                            {
                                pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                                errorMessage: '请输入正确的身份证号码'
                            }
                        ]
					},
                    email: {
						rules: [
							{
								required: true,
								errorMessage: '请输入邮箱',
							},
							{
								format: 'email',
								errorMessage: '请输入正确的邮箱'
							}
						]
					},

				},
			}
		},
		components:{

		},
		onLoad(params) {
			this.getCity()
		},
		methods:{
			onnodeclick(e) {
				this.formData.districtId = e.id
			},
			onpopupopened(e) {
				console.log('popupopened');
			},
			onpopupclosed(e) {
				console.log('popupclosed');
			},
			onchange(e) {
				console.log('onchange:', e);
			},
			getCity(){
                let areaRows = [
                    {
                        "id": 130000,
                        "status": 1,
                        "creator": null,
                        "creationTime": null,
                        "modifier": null,
                        "modificationTime": null,
                        "districtName": "河北省",
                        "districtShortName": "河北省",
                        "parentId": 0,
                        "level": 1,
                        "sortNumber": 30,
                        "cities": [
                            {
                                "id": 130100,
                                "status": 1,
                                "creator": null,
                                "creationTime": null,
                                "modifier": null,
                                "modificationTime": null,
                                "districtName": "石家庄市",
                                "districtShortName": "石家庄",
                                "parentId": 130000,
                                "level": 2,
                                "sortNumber": 10,
                                "cities": [
                                    {
                                        "id": 130100,
                                        "status": 1,
                                        "creator": null,
                                        "creationTime": null,
                                        "modifier": null,
                                        "modificationTime": null,
                                        "districtName": "和平区",
                                        "districtShortName": "和平区",
                                        "parentId": 130001,
                                        "level": 3,
                                        "sortNumber": 10,
                                        "cities": null
                                    },
                                ]
                            },
                        ]
                    },
                    {
                        "id": 140000,
                        "status": 1,
                        "creator": null,
                        "creationTime": null,
                        "modifier": null,
                        "modificationTime": null,
                        "districtName": "山西省",
                        "districtShortName": "山西省",
                        "parentId": 0,
                        "level": 1,
                        "sortNumber": 40,
                        "cities": [
                            {
                                "id": 140100,
                                "status": 1,
                                "creator": null,
                                "creationTime": null,
                                "modifier": null,
                                "modificationTime": null,
                                "districtName": "太原市",
                                "districtShortName": "太原市",
                                "parentId": 140000,
                                "level": 2,
                                "sortNumber": 10,
                                "cities": null
                            },
                        ]
                    }
                ]
                areaRows?.map((item, index) => {
                    item.text = item.districtName;
                    item.value = item.id;
                    item.children = item.cities;
                    item.children?.map((el, inde) => {
                        el.text = el.districtName;
                        el.value = el.id;
                        item.children = item.cities
                    });
                });
                console.log(areaRows);
                // 试了下,只能两层
                this.cityTree = areaRows
			},
			textareaBInput(e) {
				this.textareaBValue = e.detail.value
			},
			submit(){
				console.log(this.formData);
				this.$refs.uniForm.validate().then(res=>{
					console.log('表单数据信息:', res);
				}).catch(err =>{
					console.log('表单错误信息:', err);
				})
			},
		},

	}
</script>
<style lang="scss">
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简uniapp必填校验案例: ```html <template> <form> <div> <label for="username">用户名:</label> <input type="text" name="username" v-model="form.username" /> <span v-if="errors.username" class="error">{{ errors.username }}</span> </div> <div> <label for="password">密码:</label> <input type="password" name="password" v-model="form.password" /> <span v-if="errors.password" class="error">{{ errors.password }}</span> </div> <button type="submit" @click.prevent="submitForm">提交</button> </form> </template> <script> export default { data() { return { form: { username: '', password: '' }, errors: {} } }, methods: { validateForm() { this.errors = {} if (!this.form.username) { this.errors.username = '请填写用户名' } if (!this.form.password) { this.errors.password = '请填写密码' } return Object.keys(this.errors).length === 0 }, submitForm() { if (this.validateForm()) { console.log('验证通过,提交数据:', this.form) } } } } </script> <style> .error { color: red; } </style> ``` 在上面的代码中,我们首先定义了一个包含用户名和密码的,以及一个错误对象 `errors`。在 `validateForm` 方法中,我们通过判断中的用户名和密码是否为空来设置对应的错误信息,并返回一个布尔值来是否通过验证。在点击提交按钮时,我们调用 `validateForm` 方法进行验证,如果验证通过,则打印数据,否则不做任何操作。同时,我们使用 `v-if` 指令根据 `errors` 对象中的错误信息来渲染错误提示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值