使用 formik 进行文件名验证 yup

发布于 2025-01-16 12:54:47 字数 205 浏览 1 评论 0原文

我正在使用 YUP 和正则表达式应用文件名验证。每次上传文件时都会显示错误,文件名不应以特殊字符开头。请参考codesandbox链接:代码链接< /a> 并查看行号。 22

I am applying file name validations using YUP with regex. It's showing an error every time when the file is uploaded, the file name should not start with special characters. Please refer to the codesandbox link: Link to Code and see line no. 22

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2025-01-23 12:54:49

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

^ 断言字符串开头的位置

0-9 匹配 0 到 9 范围内的单个字符(大小写
敏感)

az 匹配 a 和 z 之间的单个字符(大小写
敏感)

AZ 匹配 A 和 Z 之间的单个字符(大小写
敏感)

. 匹配任何字符(行终止符除外)

* 与前一个标记匹配零次到无限次,如下所示
尽可能多次,根据需要回馈(贪婪)

现在要使其在您的示例中工作,您需要检查 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 ,所以请看一下

The regex you need will be ^[0-9a-zA-Z].*, a little explanation of why and how:

^ 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)

Now to make it work in your example you need to check if value.name will match said regex, this is how you can achieve this:

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].*/);
      }
    )

Once you will try to upload something that will have special characters at the start it should show error.

I have updated also codesandbox, so please have a look

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文