簡體   English   中英

用 yup 進行條件驗證

[英]conditional validation with yup

我在一個表單中有 3 個字段,“類型”字段是 select,從該列表中,一些項目啟用或禁用“輸出”字段,如果啟用,我需要“輸出”字段小於“輸入”字段反之亦然,但如果“out”字段被禁用,我不需要驗證,我正在嘗試一些東西。什么時候,但沒有工作,關於如何做到這一點的任何想法?

  const [disableOutCounterField, setDisableOutCounterField] = useState(false);

  const schema = yup.object().shape({
    type: yup.string().required(requiredMessage),
    in: yup
      .number(numberMessage)
      .required(requiredMessage)
      .integer(integerMessage)
      .min(1, positiveMessage)
      .typeError(numberMessage)
      .when("out", {
        is: !disableOutCounterField,
        then: yup.number().moreThan(yup.ref("out"), moreThanMessage),
        message: moreThanMessage,
      }),
    out: yup
      .number(numberMessage)
      .integer(integerMessage)
      .typeError(numberMessage)
      .lessThan(yup.ref("in"), lessThanMessage),
  });

構造:

.when("out", {
  is: !disableOutCounterField,

out值與!disableOutCounterField進行比較,如果它們相等,則應用then規則。 但很可能它們永遠不會相同。

對於out的任何值,此處需要的檢查只是!disableOutCounterField本身的值。 這可以使用表達式來完成:

.when("out", {
  is: value => !disableOutCounterField,

換句話說:對於每個out值,返回!disableOutCounterField ,如果它返回 true,則應用then部分。

我為此找到的另一種方法是從 useEffect 中重新生成useEffect validationSchema

這有使用useState的好處,而無需提前將它們映射到特定的表單字段,例如,如果您有條件地從數據庫中設置某些內容並且不想將其設置為某處的隱藏字段。

const validationPiece = yup.object({
amount: yup
  .number()
  .typeError('Please enter an amount')
  .required('Please enter an amount')
});

const [validationSchema, setValidaitonSchema] = useState(yup.object({}));

const {
  register,
  handleSubmit,
  reset,
  formState: { errors },
} = useForm({
  resolver: yupResolver(validationSchema),
});

useEffect(() => {
  if (needNewPartOfForm) {
    const validationSchemaDict = {};
    if (needNewPartOfForm.xyz) {
      validationSchemaDict['xyz'] = validationPiece; // does this need a cloneDeep?
    }
    if (needNewPartOfForm.abc) {
      validationSchemaDict['abc'] = validationPiece;
    }
    setValidaitonSchema(yup.object(validationSchemaDict));
  }
}, [clientDocs, clientId, reset, teamId]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM