<template>
<div>
<input type="text" v-model="inputDate" @input="validateAndConvertDate" />
<div v-if="errorMessage" style="color: red;">{{ errorMessage }}</div>
<div v-if="convertedDate">Converted Date: {{ convertedDate }}</div>
</div>
</template>
<script>
export default {
data() {
return {
inputDate: '',
errorMessage: '',
convertedDate: ''
};
},
methods: {
isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
},
isValidDate(year, month, day) {
const daysInMonth = [31, this.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth[month - 1];
},
validateAndConvertDate() {
const dateRegex = /^(?:(\d{4})([-/.])?(\d{1,2})?\2?(\d{1,2}))$/;
if (dateRegex.test(this.inputDate)) {
this.errorMessage = '';
const matches = this.inputDate.match(dateRegex);
let year = matches[1];
let month = matches[3];
let day = matches[4];
if (!month && !day) {
month = this.inputDate.substring(4, 6);
day = this.inputDate.substring(6, 8);
}
month = parseInt(month, 10);
day = parseInt(day, 10);
if (this.isValidDate(year, month, day)) {
month = month.toString().padStart(2, '0');
day = day.toString().padStart(2, '0');
this.convertedDate = `${year}-${month}-${day}`;
} else {
this.errorMessage = '输入的日期不合法。';
this.convertedDate = '';
}
} else {
this.errorMessage = '日期格式不正确,请输入xxxx.xx.xx、xxxx-xx-xx、xxxxxxxx、xxxx.x.x、xxxx-x-x格式的时间。';
this.convertedDate = '';
}
}
}
};
</script>
vue 一个包含xxxx.xx.xx、xxxx-xx-xx、xxxxxxxx、xxxx.x.x、xxxx-x-x格式的时间校验输入框,并且校验通过后把格式转成xxxx-xx-xx
最新推荐文章于 2024-08-29 21:07:49 发布