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' }
	],
	...
}
  • 31
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值