亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Yup 訪問必填字段

使用 Yup 訪問必填字段

鳳凰求蠱 2023-05-25 18:04:19
我使用帶有 yup 的 react-hook-form 來驗證我的表單。我想知道模式的所有必填字段以在表單中顯示一些信息(如必填字段的“*”)。我們可以用這行代碼來實現:schema.describe().fields[field].tests.findIndex(({ name }) => name === 'required'但是,此代碼不適用于條件驗證。架構示例:const schema = yup.object().shape({    email: yup    .string()    .email()    .required(),    isProfileRequired: yup    .boolean(),    profile:  yup    .object()    .when('isProfileRequired',{        is: (isProfileRequired) => isProfileRequired,        then:            yup            .object()            .nullable()            .required()    })})有沒有辦法在表單中檢索這些信息?
查看完整描述

3 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

實際上沒有“好的”方法來做到這一點,但這有效:

function isRequired(field){
    return schema.fields[field]._exclusive.required || false
     }

注意:schema.fields[field]._exclusive.required如果需要或未定義,則返回 true。


查看完整回答
反對 回復 2023-05-25
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

測試 exclusiveTests 而不是 _exclusive 對我有用。


const isRequired = 

validationSchema?.fields[aField.name]?.exclusiveTests?.required || false;


查看完整回答
反對 回復 2023-05-25
?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

const isFieldRequired = (validationSchema, id) =>

? validationSchema

? ? .describe()

? ? .fields[id].tests.some(({ name }) => name === 'required')

test這將檢查特定字段中是否有name等于'required'. 例如:


const validationSchema: AnyObject = object({

? username: string().required(),

? email: string().email().required(),

})

將產生一個看起來像這樣的模式fields:


{

? username: {

? ? ...

? ? tests: [

? ? ? {name: 'required', ...}, // is required

? ? ]

? },

? email: {

? ? ...

? ? tests: [

? ? ? {name: 'email', ...},

? ? ? {name: 'required', ...}, // is required

? ? ]

? },

}


查看完整回答
反對 回復 2023-05-25
  • 3 回答
  • 0 關注
  • 229 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號