如何在 Yup 中检查日期的格式是否有效?

4

我正在使用 yup 库来验证输入字段中的值:

const dateToCheck = yup
    .date()
    .nullable()
    .transform((curr, orig) => (orig === '' ? null : curr))
    .required()
    .min(minDate, 'Date cannot be this early')
    .max(maxDate, 'Date too much in the future')
    .test('format', 'Date is invalid', date => (date?.getFullYear() ?? 0) <= 9999)

我一直在尝试找出如何检查输入日期格式是否正确的方法?由于 yup 的工作方式,01.01.20002000/01/01都将通过 date验证,但我希望只允许dd.MM.yyyy格式或者yyyy/MM/dd格式通过,而不是两者都可以通过,其他任何格式如果有效则标记为无效。在 yup 中正确的方法是什么?


也许可以使用正则表达式和.matches()方法? - protob
@protob我应该在.test方法中使用它吗? - Alex T
.matches()是yup中的一个单独方法,但你也可以在test方法回调中编写正则表达式。 - protob
@protob 当你像我上面那样检查值是否为.date()时,.matches()方法将无法工作。 - Alex T
2个回答

0
作为显示格式不正确时的替代方法,您可以将输入日期更改为所需格式。以下示例将解析所有日期为yyyy-MM-dd格式:
import { parse, isDate } from "date-fns";

function parseDateString(value, originalValue) {
  const parsedDate = isDate(originalValue)
    ? originalValue
    : parse(originalValue, "yyyy-MM-dd", new Date());

  return parsedDate;
}

来源:https://www.codedaily.io/tutorials/Yup-Date-Validation-with-Custom-Transform


1
你可以在回答中提到,你刚刚从这里复制了代码:https://www.codedaily.io/tutorials/Yup-Date-Validation-with-Custom-Transform - Roar S.

-1

您可以通过在 .test() 方法后链接 .matches() 方法,将这些正则表达式验证添加到现有的 Yup 模式中。

const dateToCheck = yup
.date()
.nullable()
.transform((curr, orig) => (orig === '' ? null : curr))
.required()
.min(minDate, 'Date cannot be this early')
.max(maxDate, 'Date too much in the future')
.test('format', 'Date is invalid', date => (date?.getFullYear() ?? 0) <= 9999)
.matches(/^([0-9]{2})\.([0-9]{2})\.([0-9]{4})$/, 'Date must be in format dd.MM.yyyy');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接