[英]Yup dynamic validation chain
我正在使用 yup 驗證並嘗試構建一個條件驗證對象。
我的問題是,如何在不對其進行硬編碼的情況下將所需的和匹配的對象添加到 Yup.string() 對象中。 類似於鏈接 jQuery 函數的方式。
這是我要實現的目標的示例:
if (field.required) {
valSchema[id] = Yup.string().required(errorText[id].default);
}
if (field.validation) {
valSchema[id] = Yup.string().matches(re, field.validation[0].message);
}
if (field.otherValidation) {
valSchema[id] = Yup.string().matches(re, field.validation[1].message);
}
顯然這是行不通的,因為最后一個條件為真將覆蓋前一個條件。
如果所有條件都為真,那么最終結果會是這樣。
valSchema[id] = Yup.string()
.required(errorText[id].default)
.matches(reExp, field.validation[0].message);
.matches(reExp1, field.validation[1].message);
有任何想法嗎?
謝謝。
要有條件地添加/鏈接驗證,您可以使用 Yup 的.when
方法。
此方法還可以添加正被驗證,或者通過值的基於斷條件的驗證context
可以作為一個選項參數兩者來傳遞的對象.validate
和.isValid
呼叫。
我為您的代碼創建了以下簡化示例。 該解決方案利用了驗證期間傳入的 Yup context
對象。 使用$
符號引用上下文對象的鍵。
const schema = yup.object({
name: yup.string()
.when('$required', (required, schema) => (required ? schema.required() : schema))
.when('$regex1', (regex1, schema) => (regex1 ? schema.matches(/j/) : schema))
.when('$regex2', (regex2, schema) => (regex2 ? schema.matches(/oe/) : schema))
});
提供以下對象作為上下文將為您提供所有條件都為真的問題的最終結果:
{
required: true,
regex1: true,
regex2: true,
}
將它們放在一起為您提供以下工作示例:
const yup = require("yup");
const schema = yup.object({
name: yup.string()
.when('$required', (required, schema) => (required ? schema.required() : schema))
.when('$regex1', (regex1, schema) => (regex1 ? schema.matches(/j/) : schema))
.when('$regex2', (regex2, schema) => (regex2 ? schema.matches(/oe/) : schema))
});
const myObject = {
name: "joe",
}
const name = await schema.validate(myObject, {
context: {
required: true,
regex1: true,
regex2: true,
}
});
console.log(name); // { name: "joe" }
在此處查看和測試 RunKit 上的實時代碼: https ://runkit.com/joematune/6138a7db98ff810008ef37ab
我動態構建整個 yup 對象。 這適用於動態鏈接:
const schema = {};
fields.forEach(f => {
switch(f.dataType){
case "string":
schema[f.id] = Yup.string();
if (f.required) schema[f.id] = schema[f.id].required();
if (f.min) schema[f.id] = schema[f.id].min(f.min);
}
});
return Yup.object().shape(schema);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.