场景

Form 组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,并将 Form-Item 的 prop 属性设置为需校验的字段名即可。

官方示例代码

<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"><el-form-item label="活动名称" prop="name"><el-input v-model="ruleForm.name"></el-input></el-form-item><el-form-item label="活动区域" prop="region"><el-select v-model="ruleForm.region" placeholder="请选择活动区域"><el-option label="区域一" value="shanghai"></el-option><el-option label="区域二" value="beijing"></el-option></el-select></el-form-item><el-form-item label="活动时间" required><el-col :span="11"><el-form-item prop="date1"><el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker></el-form-item></el-col><el-col class="line" :span="2">-</el-col><el-col :span="11"><el-form-item prop="date2"><el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker></el-form-item></el-col></el-form-item><el-form-item label="即时配送" prop="delivery"><el-switch v-model="ruleForm.delivery"></el-switch></el-form-item><el-form-item label="活动性质" prop="type"><el-checkbox-group v-model="ruleForm.type"><el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox><el-checkbox label="地推活动" name="type"></el-checkbox><el-checkbox label="线下主题活动" name="type"></el-checkbox><el-checkbox label="单纯品牌曝光" name="type"></el-checkbox></el-checkbox-group></el-form-item><el-form-item label="特殊资源" prop="resource"><el-radio-group v-model="ruleForm.resource"><el-radio label="线上品牌商赞助"></el-radio><el-radio label="线下场地免费"></el-radio></el-radio-group></el-form-item><el-form-item label="活动形式" prop="desc"><el-input type="textarea" v-model="ruleForm.desc"></el-input></el-form-item><el-form-item><el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button><el-button @click="resetForm('ruleForm')">重置</el-button></el-form-item>
</el-form>
<script>export default {data() {return {ruleForm: {name: '',region: '',date1: '',date2: '',delivery: false,type: [],resource: '',desc: ''},rules: {name: [{ required: true, message: '请输入活动名称', trigger: 'blur' },{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],region: [{ required: true, message: '请选择活动区域', trigger: 'change' }],date1: [{ type: 'date', required: true, message: '请选择日期', trigger: 'change' }],date2: [{ type: 'date', required: true, message: '请选择时间', trigger: 'change' }],type: [{ type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }],resource: [{ required: true, message: '请选择活动资源', trigger: 'change' }],desc: [{ required: true, message: '请填写活动形式', trigger: 'blur' }]}};},methods: {submitForm(formName) {this.$refs[formName].validate((valid) => {if (valid) {alert('submit!');} else {console.log('error submit!!');return false;}});},resetForm(formName) {this.$refs[formName].resetFields();}}}
</script>

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先新建一个form

      <el-form ref="form" :model="form" :rules="rules" label-width="100px"><el-row><el-col span="10"><el-form-item label="班次编号:" prop="bcbh"><el-input v-model="form.bcbh" placeholder="请输入班次编号" /></el-form-item></el-col><el-col span="10"><el-form-item label="班次名称:" prop="bcmc" label-width="100px"><el-input v-model="form.bcmc" placeholder="请输入班次名称" /></el-form-item></el-col></el-row><el-row><el-col span="10"><el-form-item label="班次类型:" prop="bclx"><el-select v-model="form.bclx" placeholder="请选择班次类型" clearable @change="bclxChange"><el-optionv-for="dict in bclxOptions":key="dict.dictValue":label="dict.dictLabel":value="dict.dictValue"/></el-select></el-form-item></el-col></el-row><el-row><el-col span="10"><el-form-item label="小时数:" prop="xss"><el-input-numberv-model="form.xss":precision="1":step="1":max="24"placeholder="请输入小时数"></el-input-number></el-form-item></el-col></el-row><el-row><el-col span="10"><el-form-item label="计工数:" prop="jgs" span="10"><el-input-numberv-model="form.jgs":precision="1":step="1":max="24"placeholder="请输入计工数"></el-input-number></el-form-item></el-col></el-row>
</el-form>

在form上设置rules验证规则

:rules="rules"

绑定的是一个对象数组,所以在data中

      // 表单校验rules: {bcbh: [{ required: true, message: "班次编号不能为空", trigger: "blur" },],bcmc: [{ required: true, message: "班次名称不能为空", trigger: "blur" },],bclx: [{ required: true, message: "请选择班次类型", trigger: "blur" }],xss: [{required: true,message: "小时数不能为空",trigger: "blur",},],jgs: [{ required: true, message: "计工数不能为空", trigger: "blur" }],},

这里的格式是固定的,下面的bcbh要与上面要验证的prop相对应。

这里设置的规则都是要求必填,触发都是失去焦点。

更多校验规则参考如下:

https://github.com/yiminghe/async-validator

下面是英文原文

Usage

Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to the validate method of the schema:

import Schema from 'async-validator';
const descriptor = {name: {type: 'string',required: true,validator: (rule, value) => value === 'muji',},age: {type: 'number',asyncValidator: (rule, value) => {return new Promise((resolve, reject) => {if (value < 18) {reject('too young');  // reject with error message} else {resolve();}});},},
};
const validator = new Schema(descriptor);
validator.validate({ name: 'muji' }, (errors, fields) => {if (errors) {// validation failed, errors is an array of all errors// fields is an object keyed by field name with an array of// errors per fieldreturn handleErrors(errors, fields);}// validation passed
});// PROMISE USAGE
validator.validate({ name: 'muji', age: 16 }).then(() => {// validation passed or without error message
}).catch(({ errors, fields }) => {return handleErrors(errors, fields);
});

API

Validate

function(source, [options], callback): Promise
  • source: The object to validate (required).
  • options: An object describing processing options for the validation (optional).
  • callback: A callback function to invoke when validation completes (required).

The method will return a Promise object like:

  • then(),validation passed
  • catch({ errors, fields }),validation failed, errors is an array of all errors, fields is an object keyed by field name with an array of

Options

  • suppressWarning: Boolean, whether to suppress internal warning about invalid value.

  • first: Boolean, Invoke callback when the first validation rule generates an error, no more validation rules are processed. If your validation involves multiple asynchronous calls (for example, database queries) and you only need the first error use this option.

  • firstFields: Boolean|String[], Invoke callback when the first validation rule of the specified field generates an error, no more validation rules of the same field are processed. true means all fields.

Rules

Rules may be functions that perform validation.

function(rule, value, callback, source, options)
  • rule: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a field property with the name of the field being validated.
  • value: The value of the source object property being validated.
  • callback: A callback function to invoke once validation is complete. It expects to be passed an array of Error instances to indicate validation failure. If the check is synchronous, you can directly return a false or Error or Error Array.
  • source: The source object that was passed to the validate method.
  • options: Additional options.
  • options.messages: The object containing validation error messages, will be deep merged with defaultMessages.

The options passed to validate or asyncValidate are passed on to the validation functions so that you may reference transient data (such as model references) in validation functions. However, some option names are reserved; if you use these properties of the options object they are overwritten. The reserved properties are messagesexception and error.

import Schema from 'async-validator';
const descriptor = {name(rule, value, callback, source, options) {const errors = [];if (!/^[a-z0-9]+$/.test(value)) {errors.push(new Error(util.format('%s must be lowercase alphanumeric characters', rule.field),));}return errors;},
};
const validator = new Schema(descriptor);
validator.validate({ name: 'Firstname' }, (errors, fields) => {if (errors) {return handleErrors(errors, fields);}// validation passed
});

It is often useful to test against multiple validation rules for a single field, to do so make the rule an array of objects, for example:

const descriptor = {email: [{ type: 'string', required: true, pattern: Schema.pattern.email },{ validator(rule, value, callback, source, options) {const errors = [];// test if email address already exists in a database// and add a validation error to the errors array if it doesreturn errors;},},],
};

Type

Indicates the type of validator to use. Recognised type values are:

  • string: Must be of type stringThis 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 Date
  • url: Must be of type url.
  • hex: Must be of type hex.
  • email: Must be of type email.
  • any: Can be any type.

Required

The required rule property indicates that the field must exist on the source object being validated.

Pattern

The pattern rule property indicates a regular expression that the value must match to pass validation.

Range

A range is defined using the min and max properties. For string and array types comparison is performed against the length, for number types the number must not be less than min nor greater than max.

Length

To validate an exact length of a field specify the len property. For string and array types comparison is performed on the length property, for the number type this property indicates an exact match for the number, ie, it may only be strictly equal to len.

If the len property is combined with the min and max range properties, len takes precedence.

Enumerable

Since version 3.0.0 if you want to validate the values 0 or false inside enum types, you have to include them explicitly.

To validate a value from a list of possible values use the enum type with a enum property listing the valid values for the field, for example:

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

Whitespace

It is typical to treat required fields that only contain whitespace as errors. To add an additional test for a string that consists solely of whitespace add a whitespace property to a rule with a value of true. The rule must be a string type.

You may wish to sanitize user input instead of testing for whitespace, see transform for an example that would allow you to strip whitespace.

Deep Rules

If you need to validate deep object properties you may do so for validation rules that are of the object or array type by assigning nested rules to a fields property of the rule.

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
});

Note that if you do not specify the required property on the parent rule it is perfectly valid for the field not to be declared on the source object and the deep validation rules will not be executed as there is nothing to validate against.

Deep rule validation creates a schema for the nested rules so you can also specify the options passed to the schema.validate() method.

const descriptor = {address: {type: 'object',required: true,options: { first: 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: {} }).catch(({ errors, fields }) => {// now only errors for street and name    });

The parent rule is also validated so if you have a set of rules such as:

const descriptor = {roles: {type: 'array',required: true,len: 3,fields: {0: { type: 'string', required: true },1: { type: 'string', required: true },2: { type: 'string', required: true },},},
};

And supply a source object of { roles: ['admin', 'user'] } then two errors will be created. One for the array length mismatch and one for the missing required array entry at index 2.

defaultField

The defaultField property can be used with the array or object type for validating all values of the container. It may be an object or array containing validation rules. For example:

const descriptor = {urls: {type: 'array',required: true,defaultField: { type: 'url' },},
};

Note that defaultField is expanded to fields, see deep rules.

Transform

Sometimes it is necessary to transform a value before validation, possibly to coerce the value or to sanitize it in some way. To do this add a transform function to the validation rule. The property is transformed prior to validation and re-assigned to the source object to mutate the value of the property in place.

import Schema from 'async-validator';
const descriptor = {name: {type: 'string',required: true,pattern: /^[a-z]+$/,transform(value) {return value.trim();},},
};
const validator = new Schema(descriptor);
const source = { name: ' user  ' };
validator.validate(source).then(() => assert.equal(source.name, 'user'));

Without the transform function validation would fail due to the pattern not matching as the input contains leading and trailing whitespace, but by adding the transform function validation passes and the field value is sanitized at the same time.

Messages

Depending upon your application requirements, you may need i18n support or you may prefer different validation error messages.

The easiest way to achieve this is to assign a message to a rule:

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

Message can be any type, such as jsx format.

{ name: { type: 'string', required: true, message: '<b>Name is required</b>' } }

Message can also be a function, e.g. if you use vue-i18n:

{ name: { type: 'string', required: true, message: () => this.$t( 'name is required' ) } }

Potentially you may require the same schema validation rules for different languages, in which case duplicating the schema rules for each language does not make sense.

In this scenario you could just provide your own messages for the language and assign it to the schema:

import Schema from 'async-validator';
const cn = {required: '%s 必填',
};
const descriptor = { name: { type: 'string', required: true } };
const validator = new Schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);
...

If you are defining your own validation functions it is better practice to assign the message strings to a messages object and then access the messages via the options.messages property within the validation function.

asyncValidator

You can customize the asynchronous validation function for the specified field:

const fields = {asyncField: {asyncValidator(rule, value, callback) {ajax({url: 'xx',value: value,}).then(function(data) {callback();}, function(error) {callback(new Error(error));});},},promiseField: {asyncValidator(rule, value) {return ajax({url: 'xx',value: value,});},},
};

validator

You can custom validate function for specified field:

const fields = {field: {validator(rule, value, callback) {return value === 'test';},message: 'Value is not equal to "test".',},field2: {validator(rule, value, callback) {return new Error(`${value} is not equal to 'test'.`);},},arrField: {validator(rule, value) {return [new Error('Message 1'),new Error('Message 2'),];},},
};

FAQ

How to avoid warning

import Schema from 'async-validator';
Schema.warning = function(){};

How to check if it is true

Use enum type passing true as option.

{type: 'enum',enum: [true],message: '',
}

EelemntUI中e-form表单校验的使用以及表单校验的规则相关推荐

  1. Java入力项目无法设定到form_html中关于form与表单提交操作的资料集合

    原标题:html中关于form与表单提交操作的资料集合 这里我们介绍一下form元素与表单提交方面的知识. form元素 form元素的DOM接口是HTMLFormElement,继承自HTMLEle ...

  2. button layui 点击事件_解决layui中的form表单与button的点击事件冲突问题

    解决layui中的form表单与button的点击事件冲突问题 layui的form表单位置和button标签的位置重合,会使得button的click事件得不到响应,如图: 蓝色底为form的位置, ...

  3. HTML中的form表单有一个关键属性 enctype

    HTML中的form表单有一个关键属性 enctype=application/x-www-form-urlencoded 或multipart/form-data. 1.enctype=" ...

  4. antd-vue中的form表单label标签for导致点击文字触发输入框解决方案

    antd-vue中的form表单label标签for导致点击文字触发输入框解决方案 参考文章: (1)antd-vue中的form表单label标签for导致点击文字触发输入框解决方案 (2)http ...

  5. 在微信小程序中提交form表单

    怎么在微信小程序中提交form表单 发布时间:2021-04-07 16:26:31 来源:亿速云 阅读:1229 作者:Leah 栏目:web开发 活动:亿速云新用户活动,各类服务器大降价,满足绝大 ...

  6. HTML中的form表单及其提交原理

    HTML中的form表单 form属性 表单内容数据类型 表单控件 input表单控件 type属性 其他属性 button表单控件 label表单控件 表单组件 select option 表单提交 ...

  7. js中创建form表单

    有的时候需要在js中创建form向controller提交数据,下面是在工作中遇到的一些问题和解决办法: 简单的用jquery创建form: var form = $("<form m ...

  8. 微信小程序中使用form表单

    首先,我同事说微信小程序中不能使用form.what?他妈的逗我呢.那么多数据一个一个的赋值不麻烦么?怎么可能.只是自作做一下了.看了一下文档,就有form的组件,也给了案例.心中千万个..... 不 ...

  9. html表单action属性值,HTML中的form表单中的action属性

    用户提问 在一本书中,在一个处理用户注册的html里,作者把action的值设为"regist.jsp",如下: function on_submit() { if (form1. ...

  10. element手机验证格式_基于Vue+elementUI实现动态表单的校验功能(根据条件动态切换校验格式)...

    前言 开发过程中遇到了一个需求,根据用户选择的联系方式,动态改变输入框的检验条件,并且整个表单是可以增加的 在线访问:动态表单校验 github(欢迎star): https://github.com ...

最新文章

  1. 这次终于彻底理解了傅里叶变换
  2. Java 客户端界面功能:停止当前操作
  3. Swift 初见(A Swift Tour)
  4. matlab列优先与高维矩阵重构 及 CNN 逐层可视化 on Matlab
  5. 配置python虚拟环境心得
  6. 理解 static 关键字
  7. Java comparator接口源码解读
  8. pe如何自动加载外置工具_winpe无法加载外置程序解决方法
  9. Unity 性能优化归纳
  10. pycharm显示中间变量
  11. PyQt5 基本语法(一):基类控件
  12. 针对 Windows 和 WSUS 的 2019 SHA-2 代码签名支持要求
  13. ImprovedGAN论文略读
  14. UE4 Datasmith图标消失解决
  15. java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.SpecialProvider 使用MySqlMapper的问题
  16. 超微A+ Server 4124GS-TNR做主板集成RAID
  17. 互联网金融风控大数据技术应用
  18. USACO 3.2 Sweet Butter 香甜的黄油
  19. Win10与Ubuntu双系统设置开机启动项
  20. wifi定位技术的优势

热门文章

  1. 前缀、中缀和后缀表达式详解,中缀表达式到后缀表达式的转换规则,以及后缀表达式的计算规则,附计算代码
  2. All are Same 思维,gcd
  3. Docker环境运行Vue项目
  4. python threading lock_python threading之死锁和可重入锁
  5. c语言产生随机数_C语言 求的近似值
  6. 吐血整理:Java线程池源码分析(基于JDK1.8建议收藏)
  7. 计算机计算各科及格率,某两个班数学考试成绩如下,要求计算分析指标,用..._投资分析考试_帮考网...
  8. python修改html的td_python3修改HTMLTestRunner,生成有截图的测试报告,并发送测试邮件(一)...
  9. sql 发送邮件网络附件_利用VBA发送附件电子邮件
  10. php7 redis长连接,php使用redis长连接有哪些步骤