为什么我的yup字符串数组验证模式不工作?



有人知道为什么这不起作用吗?我有一个模式我试图与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'),
});

我还尝试添加所需和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是一个数组,但不强制它必须是字符串数组。数组的数字,布尔值等都通过这个验证。我不知道我做错了什么,在网上找不到关于这个问题的任何东西。

被验证的数据是要求。Body以json形式由postman发送,我以为有某种类型强制转换但当我检查数据类型时它返回数字,布尔值等,完全通过了我的验证

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')
});

最新更新