簡體   English   中英

為什么我的 yup 字符串數組驗證模式不起作用?

[英]Why is my yup string array validation schema not working?

有誰知道為什么這不起作用? 我有一個模式我試圖用 yup 強制執行並確保數組中的數據是字符串,這里是 yup 模式:

 signUpSchema: async (req, res, next) => { const signUpSchema = yup.object().shape({ username: yup.string().required('name is required').typeError('name must be a string'), email: yup.string().email('email must be a valid email').required('email is required').typeError('email must be a string'), password: yup.string().required('password is required').typeError('password must be a string'), password2: yup.string().oneOf([yup.ref('password'), null], 'Passwords must match'), isArtist: yup.boolean().required('isArtist is required').typeError('isArtist must be a boolean'), areaCode: yup.string().required('areaCode is required').typeError('areaCode must be a string'), //, WHY IS THIS NOT WORKING? VALIDATION OF DATA INSIDE ARRAY ISNT WORKING: locationTracking. yup.array().of(yup.string()).required('locationTracking is required').typeError('locationTracking must be an array'),min(1, 'locationTracking must have at least one location'); }). try { await signUpSchema.validate(req;body); next(); } catch (error) { next(error), } },

 locationTracking: yup.array().of(yup.string()).required('locationTracking is required').typeError('locationTracking must be an array').min(1, 'locationTracking must have at least one location'), });

我還嘗試添加 required 和 typeError 方法

 locationTracking: yup.array().of(yup.string().require().typeError('data must be strings')).required('locationTracking is required').typeError('locationTracking must be an array').min(1, 'locationTracking must have at least one location'), });

該模式強制 locationTracking 是一個數組,但不強制它必須是一個字符串數組。 Arrays 的數字、布爾值等都通過此驗證。 不確定我做錯了什么在網上找不到關於這個問題的任何信息。

正在驗證的數據是由 postman 作為 json 發送的 req.body,我認為發生了某種類型的強制轉換但是當我檢查數據類型時它返回數字 boolean 等,所以完全通過我的驗證

let schema = yup.array().of(yup.number().min(2));

await schema.isValid([2, 3]); // => true
await schema.isValid([1, -24]); // => false

schema.cast(['2', '3']); // => [2, 3]

參考

你的代碼

locationTracking: yup
            .array()
            .of(yup.string().min(1, 'locationTracking must have at least one location').required())
            .required('locationTracking is required')
        });

暫無
暫無

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

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