vue 写一个1949/10/01到当前时间的校验
时间: 2023-05-25 12:02:16 浏览: 63
代码实现如下:
```
<template>
<div>
<input type="text" v-model="inputDate" placeholder="请输入日期(格式:YYYY/MM/DD)">
<button @click="validateDate">校验</button>
<div v-if="isValid">{{ inputDate }} 是有效的日期</div>
<div v-else>{{ inputDate }} 不是有效的日期</div>
</div>
</template>
<script>
export default {
data() {
return {
inputDate: '',
isValid: false
}
},
methods: {
validateDate() {
const inputDateArr = this.inputDate.split('/')
const year = parseInt(inputDateArr[0])
const month = parseInt(inputDateArr[1])
const day = parseInt(inputDateArr[2])
// 判断是否符合格式要求
if (inputDateArr.length !== 3 || isNaN(year) || isNaN(month) || isNaN(day)) {
this.isValid = false
} else {
// 判断是否在1949/10/01到当前时间之间
const startDate = new Date('1949/10/01')
const currentDate = new Date()
const inputDate = new Date(this.inputDate)
if (inputDate >= startDate && inputDate <= currentDate) {
this.isValid = true
} else {
this.isValid = false
}
}
}
}
}
</script>
```
在模板中,我们实现了一个输入框和一个“校验”按钮,用户输入日期并点击按钮会触发 validateDate 方法进行校验。校验结果通过一个布尔类型的 isValid 变量控制,如果校验通过,就显示“是有效的日期”,否则显示“不是有效的日期”。
在 validateDate 方法中,我们先将用户输入的日期按照“/”进行分割,得到年月日。如果分割出来的数组长度不为 3,或者分割出来的年月日不是数字类型,说明输入的格式不正确,校验失败。
如果格式正确,我们将分割出来的年月日组成一个 Date 类型的对象,再和开始时间(1949 年 10 月 1 日)和当前时间比较,如果在这两个时间之间,说明是有效的日期,校验成功;否则就是无效的日期,校验失败。