用户输入一个日期的时候,我们如何对其做一个输入限制呢?试想一下,如果你输入一个13月份出来,直接弹框提醒你,会觉得冗余界面复杂,我们可以直接清掉这个3。此外,假如我们希望别人输入的日期格式如下:2024.01.12时,应该如何来规定呢?
QQ录屏20240112102820
首先,我们第一个想到的应该是使用正则来匹配
const regex = /^\d{4}\.\d{2}\.\d{2}$/;
除了正则外,想达到一个边输入边验证输入是否合法的效果,使用事件和监听来做。
1.首先写一个input输入框,v-model绑定一个值,对input使用@input事件。
<el-input v-model="baseData.recTime" placeholder="不填写则为系统默认时间"@input="validateAndFormatDateInput"></el-input>
2.判断哪些位是小数点,哪些位是数字,当然这儿我限制的并不完全,比如说第九位不能大于3,第九位为3时,第十位不能大于1。这里只是给大家做一个参考:
validateAndFormatDateInput() {// 获取输入框的值let inputValue = this.baseData.recTime || '';// 一边输入一边判断if ((inputValue.length === 5 && inputValue[4] !== '.') || // 第五位不是小数点(inputValue.length === 8 && inputValue[7] !== '.') || // 第八位不是小数点(inputValue.length === 1 && isNaN(parseInt(inputValue[0]))) ||// 第一位不是数字(inputValue.length === 2 && isNaN(parseInt(inputValue[1]))) ||(inputValue.length === 3 && isNaN(parseInt(inputValue[2]))) ||(inputValue.length === 4 && isNaN(parseInt(inputValue[3]))) ||(inputValue.length === 6 && parseInt(inputValue[5]) > 1) || // 第六位大于1(inputValue.length === 9 && parseInt(inputValue[8]) > 3) // 第九位大于3) {// 不符合条件,移除最后输入的字符this.baseData.recTime = inputValue.slice(0, -1);}// 只保留符合格式的字符this.baseData.recTime = this.baseData.recTime.replace(/[^\d.]/g, '');}
除此外使用watch来监听:
"baseData.recTime": {handler(newVal, oldVal) {console.log(newVal, oldVal);if ((oldVal + "").length > (newVal + "").length) {return;}clearTimeout(this.watchTimer);this.watchTimer = setTimeout(() => {this.baseData.recTime = newVal.replace(/[^\d\.\s]/g, "");let _value = newVal.replace(/[^\d.]/g, "") + ""; //去掉除开数字和小数点console.log(_value);this.baseData.recTime = _value;if (_value == 0) {this.baseData.recTime = "";return;}if (_value.length <= 4) {let _len = _value.length;if ((_value.replace(/\D/g, "") + "").length != _len) {this.baseData.recTime = _value.replace(/\D/g, "");return;}if (_value.length == 4) {this.baseData.recTime = _value + ".";}}if (_value.length > 4) {let _stepValue1 = _value.slice(0, 4);let _len = _stepValue1.length;if ((_stepValue1.replace(/\D/g, "") + "").length != _len) {this.baseData.recTime = _stepValue1.replace(/\D/g, "");return;}if (_value.length == 5) {if (_value[4] != ".") {this.baseData.recTime = _value.slice(0, 4);return;}}if (_value.length > 5) {if (_value[5] != "1" && _value[5] != "0") {this.baseData.recTime = _value.slice(0, 5);return;}if (parseInt(_value[6]) > 2 && _value[5] == "1") {this.baseData.recTime = _value.slice(0, 6);return;}if (_value.length > 7) {this.baseData.recTime = _value.slice(0, 7);return;}}}}, 100);},immediate: false,deep: true},