问题描述
我使用 formik 和 yup 在我的应用中处理表单验证。
我有 2 个相互关联的字段,比如说字段“日期”和字段“时间”。
我想在字段 'time' 中进行自定义验证,以根据字段 'date' 中的值检查一天中的时间是否已经过去
例如,今天是 2021 年 2 月 26 日上午 08 点,因此用户无法选择 8 点以下的时间。
解决方法
我使用 .when
方法解决。
date: string().required('date required'),time: string()
.required('time is require')
.matches(myCustomRegex)
.when('date',{
.is: data => date && date moment(new Date(),'x').format('DD/MM/YYYY') === moment(new Date(date),'x').format('DD/MM/YYYY')
.then: String().test(
'time','Start Time must not be less than the current time',value => {
if(value){
const currentHour = new Date().getHours();
const currentMinute = new Date().getMinutes();
const userPickHour = parseInt(value.split(':')[0],10)
const userPickMinute = parseInt(value.split(':')[1],10);
if(userPickHour < currentHour){
return false;
}else if(userPickHour === currentHour && userPickMinute <= currentMinute){
return false;
}else {
return true;
}
}
return true;
}
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>