Element 表单的 rules 验证 Number

在使用 Element 表单的时候,验证数字是很正常的需求。

Element的表单验证用的是 async-validator ,查看可以设置 type 来进行验证 number ,我最初使用的如下:

rules: {
	...
	count: [
		{ type: 'number', message: '请输入正确数据', trigger: 'blur' }
	],
	...
}

count 绑定在 el-input 上,验证的时候一直报 count 不是 number 类型的。

经过整体查看文档,发现有 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.

大致意思是 有时需要在验证之前转换值,可能是为了某些特殊需求。为此,transform 向验证规则添加一个函数,该属性在验证之前进行转换,并重新分配给源对象,以便在适当的位置改变属性的值。

所以我们可以用 Transform 解决上面的问题:

rules: {
	...
	count: [
		{ type: 'number', message: '请输入正确数据', trigger: 'blur', transform: (value) => Number(value) }
	],
	...
}

或者使用 pattern

rules: {
	...
	count: [
		{ pattern: /^-?\d+\.?\d*$/, message: '请输入正确数据', trigger: 'blur' }
	],
	...
}

你可能感兴趣的:(Element)