Val*_*kar 4 javascript arrays validation yup
我有这个架构:
\nconst YupSchema = (t: TFunction) =>\nYup.object().shape({\n name: Yup.string()\n .required('*')\n .max(49, 'max\xd0\xa1haracters' + ' 50'),\n areas: Yup.array().required('*'), \n activities: Yup.array().of(\n Yup.object().shape({\n id: Yup.string().required('*'),\n pictureGood: Yup.string().required(\n 'Required'\n ),\n pictureBad: Yup.string().required(\n 'Required'\n ),\n translations: Yup.array() /* <=== hear I need get only first element in array*/\n .of(\n Yup.object().shape({\n name: Yup.string().required('*'),\n desc: Yup.string()\n .required('*')\n .max(999, 'max\xd0\xa1haracters' + ' 1000'),\n \n locale: Yup.string()\n .required('*')\n .max(999, 'max\xd0\xa1haracters' + ' 1000')\n })\n )\n .required('Translations Required')\n })\n )\n})\nRun Code Online (Sandbox Code Playgroud)\n对于这个数据对象:
\n[{"id":"","activitiId":"1","pictureGood":[],"pictures":[],"translations":[{"generalDesc":"test","descGood":"test","descBad":"test","locale":"IT"},"generalDesc":"test","descGood":"test","descBad":"test","locale":"EN"}]}]\nRun Code Online (Sandbox Code Playgroud)\n但我只需要验证数组中的第一个元素,而不是全部。像这样:\n。
\n...
\ntranslations: Yup.array()[0]\n .of(\n Yup.object().shape({\n name: Yup.string().required('*'),\nRun Code Online (Sandbox Code Playgroud)\n...
\n感谢您的回答!
\n我想做同样的事情,一旦我按照以下方式扩展“from”对象,我就可以看到“index”属性进入: https: //github.com/DefinitelyTyped/DefinitelyTyped/issues/49512 ...但我不能无法获取索引。
因此,使用该技术(我将在下面复制以获取完整答案),我还设法扩展了来自 TextContext 的“选项”对象,然后扩展了“ValidateOptions”对象(我可以通过在浏览器中单步执行来看到它)我可以看到索引值!) - 因此我可以检查我在数组中进行测试的索引(因为它循环遍历数组中的所有项目)。
我在数组上运行这个 yup.test() ,然后简单地剔除任何不是index=0的东西(当然在react/javascript中index === 0!)。
所以我的解决方案是:
interface ValidateOptionsExtended {
options: {
index: number;
};
}
Yup.array().of(
Yup.object().shape({
outletId: yup
.string()
.trim()
.nullable()
.test('firstOutletAlwaysMandatory', 'Organisation name is required', function (item) {
const { from } = this as yup.TestContext & TestContextExtended;
const { options } = this as yup.TestContext & ValidateOptionsExtended;
// if not index 0 then exit we are not checking others here
if (options.index > 0) {
return true;
}
...check required value etc for index 0 here...
Run Code Online (Sandbox Code Playgroud)