首页 > 解决方案 > 使用 Formik 影响 Yup 中的每个字符串测试的正确方法是什么

问题描述

(这都是通过Formik完成的)

我通过从多个文件中导入来编译一个 Yup Schema:

一个典型的模式:

export const PersonalSchema = {
  name: Yup
    .string('Name must be a string')
    .required('Name is required')
    .min(3,'Name must be at least 3 characters')
    .max(250,'Name must be less than 250 characters'),
  altname: Yup
    .string('Alternative name must be a string')
    .max(250,'Alternative name must be less than 250 characters'),
}

还有一些主文件,包括两个模式,每个来自不同的文件:

const MasterSchema = Yup.object().shape({
    ...PersonalSchema,
    ...WorkSchema
})

一些架构使用.when.

我的任务是确保没有字符串包含 html 标记。实际上,大约有 30 个字符串字段。

到目前为止,我使用过:

Yup.addMethod(Yup.string, 'noHTML', function(args) {
  return this.matches(/^(?!(?:.|[\n\r])*<[a-z][a-z0-9]*\b[^>]*>)/i, args)
})

export const ExtraSchema = {
  bio: Yup
    .string()
    .max(4000,'Must be less than 4000 characters')
    .noHTML("HTML tags are not accepted"),
}

这变得很痛苦。

(是的,我知道表达并不完美)

我正在寻找一种方法来影响.string以禁止 HTML 或扩展它的方式。后者更可取,以防有一天某个领域可能允许它。

标签: reactjsstringformikyup

解决方案


推荐阅读