用戶輸入一個日期的時候,我們?nèi)绾螌ζ渥鲆粋€輸入限制呢?試想一下,如果你輸入一個13月份出來,直接彈框提醒你,會覺得冗余界面復(fù)雜,我們可以直接清掉這個3。此外,假如我們希望別人輸入的日期格式如下:2024.01.12時,應(yīng)該如何來規(guī)定呢?
QQ錄屏20240112102820
首先,我們第一個想到的應(yīng)該是使用正則來匹配
const regex = /^\d{4}\.\d{2}\.\d{2}$/;
除了正則外,想達(dá)到一個邊輸入邊驗證輸入是否合法的效果,使用事件和監(jiān)聽來做。
1.首先寫一個input輸入框,v-model綁定一個值,對input使用@input事件。
<el-input v-model="baseData.recTime" placeholder="不填寫則為系統(tǒng)默認(rèn)時間"
@input="validateAndFormatDateInput"></el-input>
?2.判斷哪些位是小數(shù)點,哪些位是數(shù)字,當(dāng)然這兒我限制的并不完全,比如說第九位不能大于3,第九位為3時,第十位不能大于1。這里只是給大家做一個參考:文章來源:http://www.zghlxwxcb.cn/news/detail-811685.html
validateAndFormatDateInput() {
// 獲取輸入框的值
let inputValue = this.baseData.recTime || '';
// 一邊輸入一邊判斷
if (
(inputValue.length === 5 && inputValue[4] !== '.') || // 第五位不是小數(shù)點
(inputValue.length === 8 && inputValue[7] !== '.') || // 第八位不是小數(shù)點
(inputValue.length === 1 && isNaN(parseInt(inputValue[0]))) ||// 第一位不是數(shù)字
(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來監(jiān)聽:文章來源地址http://www.zghlxwxcb.cn/news/detail-811685.html
"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, "") + ""; //去掉除開數(shù)字和小數(shù)點
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
},
到了這里,關(guān)于對input輸入框做日期輸入限制的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!