标签: yup

是的,验证访问parent.parent

我正在使用yup模块来验证我的表单。我想访问父级以测试该值。

我的架构:

enabled: yup.boolean(),
contactDetail: yup.object().shape({
  phoneNumber1: yup.string().nullable(),
  phoneNumber2: yup.string().nullable(),
  email: yup.string().test('email', 'test', async function() {
    // test enabled value
  })
}),
Run Code Online (Sandbox Code Playgroud)

该方法when可以在同一级别访问,而不是父级。

有人有主意吗?

javascript forms yup

9
推荐指数
2
解决办法
2万
查看次数

使用Firebase进行反应-提交Formik表单数据

我有一个React应用程序,该应用程序将Formik用于表单并将Cloud Firestore用于数据库。

我正在尝试将表单数据保存在Cloud Firestore中。我在控制台或React Inspector工具中没有任何错误,当我按Submit时,我在React Inspection工具中看到按钮变为禁用状态,然后再次启用,但是表单不会清除数据,并且数据确实无法发送到Cloud Firestore。

我的handleSubmit函数具有:

handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value),
        preregisterPlatform: formState.preregisterPlatform.value,
        resourceRequests: formState.resourceRequests.map(t => t.value),
        resourceOffers: formState.resourceOffers.map(t => t.value),
        ethicsIssue: formState.ethicsIssue.map(t => t.value),
        disclosureStatus: formState.disclosureStatus.value,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log("formvalues", payload);

    fsDB
      .collection("project")
      .add(payload)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };
Run Code Online (Sandbox Code Playgroud)

我的提交按钮有:

<div className="form-group">
                            <Button
                                variant="outline-primary"
                                type="submit"
                                id="ProjectId" …
Run Code Online (Sandbox Code Playgroud)

firebase reactjs yup google-cloud-firestore formik

9
推荐指数
1
解决办法
339
查看次数

验证 yup 中不同对象形状的数组

我正在使用 formik 进行表单验证,并在数组验证中遇到了一些问题。这是我的表单结构

{
 flow: [
  { text: "hello"
  },
  { input: "world"
  },
  { buttons: [
       'hi',
       'hello'
     ]
  }
 ]
}
Run Code Online (Sandbox Code Playgroud)

我必须为此创建验证架构。所以数组可能包含这些对象中的任何一个。

我试过这个,

export const validationSchema = yup.object().shape({
  flow: yup.array().of(
      yup.mixed().oneOf([
        {
          text: yup.string().required('Enter text'),
        },
        {
          buttons: yup.array().of(yup.string().required('Enter button title')),
        },
        {
          input: yup.string(),
        }
      ])
  ),
});
Run Code Online (Sandbox Code Playgroud)

但我收到以下 formik 错误:

flow:[

"flow[0] must be one of the following values: [object Object], [object Object]",
"flow[1] must be one of the following values: [object Object], [object Object]"

] …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs yup formik

9
推荐指数
1
解决办法
1万
查看次数

是的,当用户单击提交按钮时,不会验证复选框

我的 React 应用程序中有以下 Yup 配置:

 const schema = yup.object().shape({
        email: yup.string()
            .email('E-mail is not valid!')
            .required('E-mail is required!'),
        password: yup.string()
            .min(6, 'Password has to be longer than 6 characters!')
            .required('Password is required!'),
        tandc: yup.boolean()
            .oneOf([true], "You must accept the terms and conditions")
    })
Run Code Online (Sandbox Code Playgroud)

我的表单如下所示(使用 Formik):

 <Form>
                    <div className="form-group">
                        <label >Email
                        <Field type="email" name="email" className="form-control" />
                        </label>
                        <ErrorMessage name="email" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group">
                        <label >Password
                        <Field type="password" name="password" className="form-control"  />
                        </label>
                        <ErrorMessage name="password" component="div" className="invalid-feedback" />
                    </div>
                    <div className="form-group"> …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs yup formik

9
推荐指数
3
解决办法
4万
查看次数

是的验证;同一字段可以接受不同类型吗?

我对是的很陌生。我试图验证字段可以是遵循某个正则表达式的字符串,也可以是此类字符串的数组。

这是检查字符串与我的正则表达式匹配的工作示例

{ field: yup.string().matches(regex) }
Run Code Online (Sandbox Code Playgroud)

现在我想field如果它有一个这样的字符串数组也是有效的:

{field: yup.array().of(yup.string().matches(regex))}
Run Code Online (Sandbox Code Playgroud)

但我如何将两者结合起来呢?我试过了:

{
  field: yup.mixed().when('field', {
    is: Array.isArray,
    then: yup.array().of(yup.string().matches(regex)),
    otherwise: yup.string().matches(regex)
  })
}
Run Code Online (Sandbox Code Playgroud)

但我可以理解地得到了循环依赖错误,因为该字段依赖于自身。正确的语法是什么?

javascript validation typescript yup

9
推荐指数
1
解决办法
5258
查看次数

是的,基于非字段值的条件验证

我正在尝试创建一个 yup 模式,其中模式根据变量值略有变化。就我而言,根据 prop 的值,myCondition我需要根据需要创建一个字段。我想知道是否有更好的方法可以使用 Yup 实现相同的目的。这是我当前有效的代码结构:

// config.js
const COMMON_SCHEMA = {
  str1: yup
    .string()
    .nullable()
    .required('Please input str1'),
  str3: yup
    .string()
    .nullable()
};
const VALIDATION_SCHEMA_1 = yup.object().shape({
  ...COMMON_SCHEMA,
  str2: yup.string().nullable(),
});

const VALIDATION_SCHEMA_2 = yup.object().shape({
  ...COMMON_SCHEMA,
  str2: yup
    .string()
    .nullable()
    .required('Please input str2'),
});

const SCHEMAS = {
  VALIDATION_SCHEMA_1,
  VALIDATION_SCHEMA_2
}
export default SCHEMAS;
Run Code Online (Sandbox Code Playgroud)

以下是我有条件地选择不同模式的方法:

// app.js
import SCHEMAS from './config';
...

<Formik
  validationSchema={
    this.props.myCondition === true
      ? SCHEMAS.VALIDATION_SCHEMA_1
      : SCHEMAS.VALIDATION_SCHEMA_2
  }
>
...
</Formik>
Run Code Online (Sandbox Code Playgroud)

我觉得我可以用更简单的方式实现上面所做的任何事情 …

javascript reactjs yup formik

9
推荐指数
1
解决办法
8849
查看次数

使用 Formik 和 Yup 键入时验证用户名是否已存在

我的公司有一项任务,我必须显示用户名是否被占用,我使用 formik 和 yup 验证进行检查,所以暂时我在 yup 验证中添加了一个自定义测试功能,该功能显示用户名是否被使用单击提交按钮是否被采用,但是,我最初的任务是在用户输入用户名时动态显示错误消息,它应该告诉他用户名是否被采用。\n我明白我可能必须操作formik的默认handleChange,但我\xe2\x80\x99m无法这样做。\n非常感谢任何帮助!

\n
         validationSchema: Yup.object({\n            name: Yup.string()\n                .min(2, "Mininum 2 characters")\n                .max(30, "Maximum 30 characters")\n                .required("Your name is required"),\n            email: Yup.string()\n                .email("Invalid email format")\n                .test("email", "This email has already been registered", function (email) {\n                        return checkAvailabilityEmail(email);\n                })\n                .required("Your email is required"),\n            username: Yup.string()\n                .min(1, "Mininum 1 characters")\n                .max(15, "Maximum 15 characters")\n                .test("username", "This username has already been taken", function (username) {\n                        return checkAvailabilityUsername(username);\n                })\n                .required("You must enter a username"),\n
Run Code Online (Sandbox Code Playgroud)\n

forms reactjs yup formik

9
推荐指数
1
解决办法
9736
查看次数

(是的)如何使用单个 .test() 函数创建多个错误

编辑:虽然已接受的解决方案有效,但我的用例中效果更好

我有一个函数可以验证输入字段 A输入字段 B都不为空,并且根据我的表单的构建方式,我只需编写一个函数来检查这两个字段。(实际函数要复杂得多,所以我选择创建下面的示例函数)

这是我的测试功能:

function isValid(message) {
    //I don't use the message variable but I added it anyway
    return this.test("isValid", message, function (value) {
    if(!value.A) {
        return createError({path: `${this.path}.A`, message:"A is empty"});
    }
    if(!value.B) {
        return createError({path: `${this.path}.B`, message:"B is empty"});
    }
    return true;
    })
Run Code Online (Sandbox Code Playgroud)

这样做的结果是,当 A 和 B 为空时,我返回第一个 createError,因此函数的其余部分将被跳过,这就是formik.errors对象的样子:

{
    parent: {
        A: "A is empty"
    }
}
Run Code Online (Sandbox Code Playgroud)

如何创建错误数组并返回它?

我试过:

返回 createErrors() 数组,但我得到了相同的结果,

将 createErrors 与路径和消息数组一起使用,但 formik.errors …

javascript reactjs yup formik

9
推荐指数
1
解决办法
7169
查看次数

使用 Yup 验证非必填数字字段

我正在尝试验证一个可选的数字字段,因此允许为空。如果该字段中有值,则该值必须是正数。

const schema = yup.object().shape({
    gpa: yup.number()
        .when('gpa', {
        is: (value) => value?.length > 0,
        then: yup.number().positive(numberPositiveMessage).typeError(numberMessage),
        otherwise: yup.number().notRequired().nullable(true).transform(value => (isNaN(value) ? undefined : value))
    },
    [
        ['gpa', 'gpa'],
    ]
);
Run Code Online (Sandbox Code Playgroud)

它允许表单的其余部分在字段为空时以及其中有正数时进行验证,但如果我输入负数或字符串,它不会返回任何应有的错误。

javascript reactjs yup

9
推荐指数
1
解决办法
1万
查看次数

是的 Typescript 并集/交集验证

对于我使用yup 的项目,但我在从架构中获取良好的类型时遇到问题...理想情况下,我会得到一个类型,该类型显示当属性具有特定值时,必须定义另一个属性!

我构建了一个快速的Codesandbox来显示问题,但如果您不想切换,我也将其发布在这里......

模式定义如下

const schema = yup.object({
  contactForm: yup
    .mixed<"phone" | "email">()
    .required()
    .oneOf(["email", "phone"]),
  email: yup.string().when("contactForm", {
    is: "email",
    then: (schema) => schema.required().email(),
    otherwise: (schema) => schema.transform(() => undefined)
  }),
  phone: yup.string().when("contactForm", {
    is: "phone",
    then: (schema) => schema.required(),
    otherwise: (schema) => schema.transform(() => undefined)
  })
});
Run Code Online (Sandbox Code Playgroud)

模式类型

type Schema = yup.InferType<typeof schema>;

我得到什么:

type Schema = {
    contactForm: "email" | "phone";
    email: string | undefined;
    phone: string | undefined;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我检查具有 TypeScript 的对象时,contactForm: …

typescript yup

9
推荐指数
0
解决办法
3435
查看次数