iviewui表单验证新手教程

1、表单验证介绍

下面来讲解iviewui表单验证的实现,下面上示例代码:

<template><Form ref="formInline" :model="formInline" :rules="ruleInline" inline><FormItem prop="user"><!--prop属性不能少--><Input type="text" v-model="formInline.user" placeholder="Username"><Icon type="ios-person-outline" slot="prepend"></Icon></Input><--formInline.user关联的变量值--></FormItem><FormItem prop="password"><Input type="password" v-model="formInline.password" placeholder="Password"><Icon type="ios-lock-outline" slot="prepend"></Icon></Input></FormItem><FormItem><Button type="primary" @click="handleSubmit('formInline')">Signin</Button></FormItem></Form>
</template>
<script>export default {data () {return {formInline: {user: '',password: ''},ruleInline: {user: [{ required: true, message: 'Please fill in the user name', trigger: 'blur' }],password: [{ required: true, message: 'Please fill in the password.', trigger: 'blur' },{ type: 'string', min: 6, message: 'The password length cannot be less than 6 bits', trigger: 'blur' }]}}},methods: {handleSubmit(name) {this.$refs[name].validate((valid) => {if (valid) {this.$Message.success('Success!');} else {this.$Message.error('Fail!');}})}}}
</script>

错误演示效果如下:

表单项的props

属性说明类型默认值
prop对应表单域 model 里的字段String-
label标签文本String-
label-width表单域标签的的宽度Number-
label-for指定原生的 label 标签的 for 属性,配合控件的 element-id 属性,可以点击 label 时聚焦控件。String-
required是否必填,如不设置,则会根据校验规则自动生成Boolean-
rules表单验证规则Object | Array-
error表单域验证错误信息, 设置该值会使表单验证状态变为error,并显示该错误信息String-
show-message是否显示校验错误信息Booleantrue

 表单的props

属性说明类型默认值
model表单数据对象Object-
rules表单验证规则,具体配置查看  async-validatorObject-
inline是否开启行内表单模式Booleanfalse
label-position表单域标签的位置,可选值为 leftrighttopStringright
label-width表单域标签的宽度,所有的 FormItem 都会继承 Form 组件的 label-width 的值Number-
show-message是否显示校验错误信息Booleantrue
autocomplete原生的 autocomplete 属性,可选值为 off 或 onStringoff
hide-required-mark 4.0.0是否隐藏所有表单项的必选标记Booleanfalse
label-colon 4.0.0是否自动在 label 名称后添加冒号Booleanfalse
disabled 4.0.0是否禁用该表单内的所有组件(适用于具有 disabled 属性的表单类组件)Booleanfalse

表单的events 

事件名说明返回值
on-validate 4.0.0任一表单项被校验后触发,返回表单项 prop、校验状态、错误消息prop, status, error

表单的methods 

方法名说明参数
validate对整个表单进行校验,参数为检验完的回调,会返回一个 Boolean 表示成功与失败,支持 Promisecallback
validateField对部分表单字段进行校验的方法,参数1为需校验的 prop,参数2为检验完回调,返回错误信息callback
resetFields对整个表单进行重置,将所有字段值重置为空并移除校验结果

表单项的slot 

名称说明
内容
labellabel 内容

如下代码部分的“ruleInline”就是表单的验证规则,规则属性有哪些:

2、规则属性介绍

2.1 Type = 类型

指示type要使用的验证器。可识别的类型值为:

  • string:必须是string类型,默认类型
  • number:必须是number类型
  • boolean:必须是boolean类型
  • method:必须是function类型
  • regexp:必须是的实例RegExp或创建新的时不会产生异常的字符串RegExp
  • integer:必须是number整数类型
  • float:必须是number浮点数类型
  • array:必须是由数组Array.isArray
  • object:必须是object且不是Array.isArray
  • enum:值必须存在于enum中
  • date:值必须为Date类型
  • url:必须是url类型
  • hex:必须是hex类型
  • email:必须是email类型
  • any:可以是任意类型

2.2 Required

规则属性required表示该字段必须存在于被验证的源对象上

2.3 Pattern

规则pattern属性指示值必须匹配才能通过验证的正则表达式

2.4 Range

min使用和属性定义范围max。对于stringarray类型,比较是针对进行的length,对于number类型,数字不得小于min或大于max

2.5 Length

要验证字段的精确长度,请指定len属性。对于stringarray类型,对属性执行比较length,对于number类型,此属性表示与完全匹配number,即,它可能仅严格等于len

如果该len属性与minmax范围属性结合使用,len则优先。

2.6 Enumerable

要从可能值列表中验证一个值,请使用enum带有enum列出该字段有效值的属性的类型,例如:

const descriptor = {role: { type: 'enum', enum: ['admin', 'user', 'guest'] },
};

2.7 Whitespace

通常将仅包含空格的必填字段视为错误。要对仅由空格组成的字符串添加额外测试,请whitespace向值为 的规则添加属性true。规则必须是类型string

您可能希望清理用户输入而不是测试空格,请参阅转换以获取允许您去除空格的示例。

2.8 Deep Rules

如果您需要验证深层对象属性,则可以通过将嵌套规则分配给规则的属性来对object或类型的验证规则进行验证。arrayfields

const descriptor = {address: {type: 'object',required: true,fields: {street: { type: 'string', required: true },city: { type: 'string', required: true },zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },},},name: { type: 'string', required: true },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} }, (errors, fields) => {// errors for address.street, address.city, address.zip
});

规则示例:

{ name: { type: 'string', required: true, message: 'Name is required' } }

其它规则示例:

export default {data() {return {title: '管理平台',address: 'title.png',sendAuthCode: true, /* 布尔值,通过v-show控制显示‘获取按钮'还是‘倒计时' */auth_time: '120', /* 倒计时 计数器 */firstForm: {},thirdForm: {userName: '',account: '',password: '',email: '',telephone: '',fax: '',postCode: '',phone: '',phoneValidation: '',captchaCode: '',},captchaUrl: `${global.CTX}/captcha`,rules: {userName: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' },{ min: 1, max: 20, message: '管理员姓名在20字以内', trigger: 'blur' },],account: [{ required: true, message: '请输入管理员账号', trigger: 'blur' },{ min: 1, max: 50, message: '管理员账号在50字以内', trigger: 'blur' },{ pattern: /^\S+$/, message: '账号不允许有空格', trigger: 'blur' },],password: [{ required: true, message: '请输入长度为10-20位包含数字、字母、特殊字符的密码', trigger: 'blur' },{ pattern: /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{10,20}$/, message: '请输入长度为10-20位包含数字、字母、特殊字符的密码', trigger: 'blur' },],postCode: [{ max: 10, message: '邮编长度10位以内', trigger: 'blur' },],fax: [{ max: 50, message: '传真长度50字以内', trigger: 'blur' },],email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },{ max: 50, message: '邮箱在50字以内', trigger: 'blur' },{ pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请检查邮箱格式是否正确', trigger: 'blur' },],
//最后的校验规则,不需要自己写校验规则也可以写成 { type: 'email', message: '请检查邮箱格式是否正确', trigger: 'blur' },/*type的枚举值有string: Must be of type string. This is the default type.number: Must be of type number.boolean: Must be of type boolean.method: Must be of type function.regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.integer: Must be of type number and an integer.float: Must be of type number and a floating point number.array: Must be an array as determined by Array.isArray.object: Must be of type object and not Array.isArray.enum: Value must exist in the enum.date: Value must be valid as determined by Dateurl: Must be of type url.hex: Must be of type hex.email: Must be of type email.https://github.com/yiminghe/async-validator#type https://www.cnblogs.com/chaoxiZ/p/10136780.html
*/telephone: [{ max: 50, message: '电话长度在50位以内', trigger: 'blur' },],phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' },{ pattern: /^((1[3,5,8][0-9])|(14[5,7])|(17[0,5,6,7,8])|(19[7]))\d{8}$/, message: '请检查手机号是否正确', trigger: 'blur' },],phoneValidation: [{ required: true, message: '请输入手机验证码', trigger: 'blur' },],captchaCode: [{ required: true, message: '请输入图片验证码', trigger: 'blur' },],},};},components: {titleBar,navBar,},methods: {// 是否显示密码showPwd() {const input = document.getElementById('pwd');if (input.type === 'password') {input.type = 'text';} else if (input.type === 'text') {input.type = 'password';}},// 刷新图片验证码refresh() {this.captchaUrl = `${global.CTX}/captcha?tm=${Math.random()}`;},// 倒计时getAuthCode() {if (this.authTimeTimer) {clearTimeout(this.authTimeTimer);}this.authTimeTimer = setTimeout(() => {this.auth_time -= 1;if (this.auth_time < 0) {this.sendAuthCode = true;clearTimeout(this.authTimeTimer);} else {this.getAuthCode();}}, 1000);},// 发送短信sendMsg(phoneNum) {this.$refs.thirdForm.validateField('phone', (phoneError) => {console.log(`${phoneError}***************************`);if (!phoneError) {this.auth_time = 120;this.sendAuthCode = false;api.sendMsg({params: {params: {phone: phoneNum,reason: 'developerReg',},},}).then(() => {this.getAuthCode();this.$confirm('验证码已发送至登记手机号上,请查收。', {confirmButtonText: '确定',center: true,});}).catch((err) => {this.sendAuthCode = true;this.$message({message: err.response.message,type: 'error',});});}});},// 验证登入账号是否存在checkDevpUserAccount(account) {api.checkDevpUserAccount({params: {params: {account,},},}).then((data) => {if (data.state === 0) {this.checkCaptcha();}}).catch((err) => {this.$message({message: err.response.message,type: 'error',});});},// 图片验证码验证是否正确checkCaptcha() {api.getCaptcha({params: {params: {captchaCode: this.thirdForm.captchaCode,},},}).then(() => {this.checkSmsValidCode();}).catch((err) => {this.$message({message: err.tip,type: 'error',});this.refresh();});},// 验证短信验证码checkSmsValidCode() {api.verifySmsValidCode({params: {params: {phone: this.thirdForm.phone,reason: 'developerReg',validCode: this.thirdForm.phoneValidation,},},}).then((data) => {if (data.state === 0) {this.submit();}}).catch((err) => {this.$message({message: err.tip,type: 'error',});});},// 上一步previousStep() {sessionStorage.setItem('needSecondStepCache', '1');this.$router.push({ name: 'DeveloperSecond' });},// 下一步nextStep(thirdForm) {this.$refs[thirdForm].validate((valid) => {if (valid) {this.checkDevpUserAccount(this.thirdForm.account);}});},// 向后台提交数据submit() {if (this.firstForm.devpType === '1') {this.thirdForm.userName = this.firstForm.devpNameself;}this.secondForm.cmmiLevel = (this.secondForm.cmmiLevel === '无' ? '' : this.secondForm.cmmiLevel);this.secondForm.isoLevel = (this.secondForm.isoLevel === '无' ? '' : this.secondForm.isoLevel);const passwordTemp = md5(this.thirdForm.password);api.registeredDeveloper({params: {data: {devpType: this.firstForm.devpType,devpName: this.firstForm.devpName,devpCode: this.firstForm.devpCode,logo: this.firstForm.logo,companyAddress: this.firstForm.companyAddress,companyDescrible: this.firstForm.companyDescrible,companyBusiness: this.firstForm.companyBusiness,identifyPositiveId: this.firstForm.identifyPositiveId,identifyReverseId: this.firstForm.identifyReverseId,employeeCode: this.firstForm.employeeCode,remarks: this.firstForm.remarks,cmmiLevel: this.secondForm.cmmiLevel,isoLevel: this.secondForm.isoLevel,qualificationId: this.secondForm.qualificationId,userName: this.thirdForm.userName,account: this.thirdForm.account,password: passwordTemp,email: this.thirdForm.email,telephone: this.thirdForm.telephone,fax: this.thirdForm.fax,postCode: this.thirdForm.postCode,phone: this.thirdForm.phone,},},}).then(() => {this.$router.push({name: 'ReturnSuccessMsg',params: {},});}).catch((err) => {this.$message({message: err.response.message,type: 'error',});});},},mounted() {this.firstForm = JSON.parse(sessionStorage.getItem('firstForm')) || {};this.secondForm = JSON.parse(sessionStorage.getItem('secondForm')) || {};},
};
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/65334.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

测试测试测试测试测试测试测试测试测试测试

标题详情作者简介愚公搬代码头衔华为云特约编辑&#xff0c;华为云云享专家&#xff0c;华为开发者专家&#xff0c;华为产品云测专家&#xff0c;CSDN博客专家&#xff0c;CSDN商业化专家&#xff0c;阿里云专家博主&#xff0c;阿里云签约作者&#xff0c;腾讯云优秀博主&…

【音视频工具系列】streamEye 工具分析 H264 码流详细教程

streamEye工具 Elecard StreamEye 是一款专业的视频质量分析工具,广泛应用于视频编解码器的开发、系统集成、传输流制造等领域。它提供了对视频流的深度分析,包括宏块和帧级别的详细视觉表示。StreamEye 支持多种视频格式,如 MPEG-1/2、AVC/H.264、HEVC/H.265、VP9 等,能够…

Doris的SQL原理解析

今天来介绍下Doris的SQL原理解析&#xff0c;主要从语法、解析、分析、执行等几个方面来介绍&#xff0c;可以帮助大家对Doris底层有个清晰的理解~ 一、Doris简介 Apache Doris是一个基于MPP架构的高性能、实时的分析型数据库&#xff0c;能够较好的满足报表分析、即席查询、…

OpenHarmony开发板环境搭建

程序员Feri一名12年的程序员,做过开发带过团队创过业,擅长Java相关开发、鸿蒙开发、人工智能等,专注于程序员搞钱那点儿事,希望在搞钱的路上有你相伴&#xff01;君志所向,一往无前&#xff01; 0.OpenHarmony 0.1 OpenHarmony OpenHarmony是一款面向全场景、全连接、全智能的…

Debian12 安装配置 ODBC for GaussDB

第一步 apt install -y unixodbc 第二步下载 dws_8.2.x_odbc_driver_for_x86_redhat.zip 到 /tmp&#xff0c;之后 cd /tmp unzip dws_8.2.x_odbc_driver_for_x86_redhat.zip cp lib/* /usr/local/lib cp odbc/lib/* /usr/local/lib echo /usr/local/lib >> /etc/ld…

Web前端基础知识(四)

CSS简介 CSS(层叠样式表)&#xff0c;用于定义网页样式和布局的样式表语言。 一般与HTML一起用于构建web页面的。 HTML负责定义页面的结构和内容&#xff0c;CSS负责控制页面的外观和样式。 通过CSS&#xff0c;可以指定页面中各个元素的颜色、字体、大小、间距、边框、背景…

ESP32_h2-创建一个工程后,添加驱动文件并在调用

点击F1或者ctrlshiftP 输入组件名字&#xff1a; 创建好后&#xff0c;可以看到文件目录多了components文件夹和组件文件 &#xff08;文件夹名字uart就是组件名字&#xff09;这里更改了文件名字 在整个工程目录下找到&#xff1a; 添加路径 finish&#xff01; 调用 程…

SQL进阶技巧:如何计算加油站问题? | LeetCode 134. 加油站

目录 0 问题描述 1 数据准备 2 问题分析 计算每个加油站剩余油量(当前油量减去到下一个加油站消耗的油量)

【Android】application@label 属性属性冲突报错

错误记录 What went wrong: Execution failed for task :app:processDebugMainManifest. > Manifest merger failed : Attribute applicationlabel value(string/app_name) from AndroidManifest.xml:8:9-41is also present at [:abslibrary] AndroidManifest.xml:25:9-47 v…

idea报错:There is not enough memory to perform the requested operation.

文章目录 一、问题描述二、先解决三、后原因&#xff08;了解&#xff09; 一、问题描述 就是在使用 IDEA 写代码时&#xff0c;IDEA 可能会弹一个窗&#xff0c;大概提示你目前使用的 IDEA 内存不足&#xff0c;其实就是提醒你 JVM 的内存不够了&#xff0c;需要重新分配。弹…

深入解析:构建高效单页应用(SPA)的最佳实践与示例

文章目录 前言一、单页应用&#xff08;SPA&#xff09;的介绍二、单页应用&#xff08;SPA&#xff09;的优势三、构建单页应用&#xff08;SPA&#xff09;的基本步骤四、使用Vue.js构建一个简易的单页应用&#xff08;SPA&#xff09;&#xff1a;任务管理器结语 前言 随着…

PHP高性能webman管理系统EasyAdmin8

介绍 EasyAdmin8-webman 在 EasyAdmin 的基础上使用 webman 最新版重构&#xff0c;PHP 最低版本要求不低于 8.0。基于webman和layui v2.9.x的快速开发的后台管理系统。 项目地址&#xff1a;http://easyadmin8.top 演示地址&#xff1a;http://webman.easyadmin8.top/admin …

运算符 - 算术、关系、逻辑运算符

引言 在编程中&#xff0c;运算符是用于执行特定操作的符号。C 提供了多种类型的运算符&#xff0c;包括算术运算符、关系运算符和逻辑运算符等。理解这些运算符及其用法对于编写高效且无误的代码至关重要。本文将详细介绍 C 中的这三种基本运算符&#xff0c;并通过实例帮助读…

简单讲解关于微信小程序调整 miniprogram 后, tabbar 找不到图片的原因之一

微信小程序开发&#xff0c;[ miniprogram/app.json 文件内容错误]&#xff0c;["tabBar"]["list"][0]["iconPath"]: "/miniprogram/assets/tabbar/icon_main_home.png" 未找到 简单讲解关于调整 miniprogram 后&#xff0c; tabbar 找…

ThinkPHP 数据库操作详解:CRUD 实现与最佳实践

ThinkPHP 数据库操作详解&#xff1a;CRUD 实现与最佳实践 在现代 Web 开发中&#xff0c;数据库操作是应用程序的核心部分。ThinkPHP 作为一款流行的 PHP 框架&#xff0c;提供了强大的数据库操作功能&#xff0c;使得开发者能够高效地进行数据的增删改查&#xff08;CRUD&am…

《Ceph:一个可扩展、高性能的分布式文件系统》

大家觉得有意义和帮助记得及时关注和点赞!!! 和大多数分布式存储系统只支持单一的存储类型不同&#xff0c;Ceph 同时支持三种&#xff1a; 文件系统&#xff08;file system&#xff09;&#xff1a;有类似本地文件系统的层级结构&#xff08;目录树&#xff09;&#xff0c…

Kafka数据迁移全解析:同集群和跨集群

文章目录 一、同集群迁移二、跨集群迁移 Kafka两种迁移场景&#xff0c;分别是同集群数据迁移、跨集群数据迁移。 一、同集群迁移 应用场景&#xff1a; broker 迁移 主要使用的场景是broker 上线,下线,或者扩容等.基于同一套zookeeper的操作。 实践&#xff1a; 将需要新添加…

“智能控制的新纪元:2025年机器学习与控制工程国际会议引领变革

ICMLCE 2025 | 机器学习与控制工程国际会议 ✨宝子们&#xff0c;今天要为大家介绍的是一个在机器学习和控制工程领域备受瞩目的国际学术盛会——2025年机器学习与控制工程国际会议&#xff08;ICMLCE 2025&#xff09;。本次大会将在美丽的大理举行&#xff0c;旨在汇聚全球顶…

公路边坡安全监测中智能化+定制化+全面守护的应用方案

面对公路边坡的安全挑战&#xff0c;我们如何精准施策&#xff0c;有效应对风险&#xff1f;特别是在强降雨等极端天气下&#xff0c;如何防范滑坡、崩塌、路面塌陷等灾害&#xff0c;确保行车安全&#xff1f;国信华源公路边坡安全监测解决方案&#xff0c;以智能化、定制化为…

Julia语言的语法

深入理解Julia语言&#xff1a;高效科学计算的新宠 引言 在当今高速发展的技术环境中&#xff0c;科学计算和数据分析的需求日益增长。作为一种新兴的编程语言&#xff0c;Julia以其高效的性能和简洁的语法吸引了众多研究人员和开发者的注意。本文将深入探讨Julia语言的设计理…