表单校验在日常开发中肯定是老生常谈的问题,具体的就不展开说了,这次就是想和大家分享一种较为完美解决数值输入校验的方法...
使用Element表单的话,正常的话就是在rules属性中设置校验规则,在表单提交时进行校验,或者是在onkeyup属性中通过正则限制输入,但是onkeyup会体现出replace替换的过程,可能会带来不太友好的用户体验,还有就是仅仅使用正则不能完美地解决输入限制的需求...
接下来我分享的就是在input事件中去做输入的限制,同时能够解决onkeyup带来的一些问题... 不说了,直接粘代码...
weightIpt() {
const reg = /^[+]{0,1}(\d+\.?\d*|\.\d+)$/;
if (!reg.test(this.formData.goodWeight)) {
this.formData.goodWeight = this.formData.goodWeight.replace(/[^\d.]/g, '');
const index = this.formData.goodWeight.indexOf('.');
if (index !== -1 && this.formData.goodWeight.indexOf('.', index + 1) !== -1) {
this.formData.goodWeight = this.formData.goodWeight.substr(0, index + 1) +
this.formData.goodWeight.substr(index + 1).replace(/\./g, '');
}
}
}