使用 formik 进行文件名验证

File Name Validation using formik yup

我正在使用 YUP 和正则表达式应用文件名验证。每次上传文件都报错,文件名不能以特殊字符开头。请参考代码框 link: Link to Code 并查看行号。 22

您需要的正则表达式是 ^[0-9a-zA-Z].*,关于原因和方式的一些解释:

^ asserts position at start of the string

0-9 matches a single character in the range between 0 and 9 (case sensitive)

a-z matches a single character in the range between a and z (case sensitive)

A-Z matches a single character in the range between A and Z (case sensitive)

. matches any character (except for line terminators)

* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)

现在要让它在您的示例中运行,您需要检查 value.name 是否会匹配所述正则表达式,这就是实现此目的的方法:

validationSchema: Yup.object().shape({
  file: Yup.mixed()
    .required("file is required")
    .test(
      "fileName",
      "file name should not start with special characters",
      (value) => {
        return value.name.match(/^[0-9a-zA-Z].*/);
      }
    )

一旦您尝试上传开头有特殊字符的内容,它应该会显示错误。

我也更新了codesandbox,请看