如何使用formik和yup在需要另一个字段值的字段中创建自定义验证



我使用formik和yup来处理我的应用程序中的表单验证。

我有两个相互关联的字段,比如字段'date'和字段'time'。

我想在字段'time'中进行自定义验证,以根据字段'date'的值检查当天的时间是否已经过去

例如,今天是2021年2月26日,上午8点,因此用户不能选择低于8点的时间。

date: string().required('date required'),
time: string()
.required('time is require')
.matches(myCustomRegex)

我用.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>

最新更新