我目前正在使用 Formik 并使用 Yup 进行验证。
我希望验证 2 个日期、一个开始日期和一个结束日期。
起初这很简单,我有两个输入字段,start_date并且end_date. 这两个都只是接受以下格式的文本输入,MM-YYYY. 验证已经足够好了,它首先将该字符串转换为日期,使用moment(value, "MM-YYYY").
由此,我们进行了以下测试:
start_date: Yup.string()
.test(
'test1',
'Format must be MM-YYYY',
function (value){
return moment(value, "MM-YYYY", true).isValid()
}
)
.test(
'test2',
'Start date must be before end date',
function(value){
let { end_date } = this.parent;
return moment(value, "MM-YYYY").isBefore(moment(end_date, "MM-YYYY"))
}
)
test1只需检查 是否MM-YYYY是有效日期。test2检查 thestart_date是否在end_date. 为了简单起见,end_date测试是相同的,除了有任何额外的测试。额外测试检查end_date是否等于或小于当前日期。
这就是我目前拥有的,但是我想要的是 4 个输入框:
start_date_month(01, 02, 03...)start_date_year(2000 年、2001 年……)end_date_monthend_date_year
这很容易做到,但测试会有点不同,我不确定我们是否可以start_date_month一起测试start_date_year。本质上,我需要将它们连接起来以再次-创建MM-YYYY。
有什么想法可以用 Yup 做到这一点吗?