我有这个模式:
const YupSchema = (t: TFunction) =>
Yup.object().shape({
name: Yup.string()
.required('*')
.max(49, 'maxСharacters' + ' 50'),
areas: Yup.array().required('*'),
activities: Yup.array().of(
Yup.object().shape({
id: Yup.string().required('*'),
pictureGood: Yup.string().required(
'Required'
),
pictureBad: Yup.string().required(
'Required'
),
translations: Yup.array() /* <=== hear I need get only first element in array*/
.of(
Yup.object().shape({
name: Yup.string().required('*'),
desc: Yup.string()
.required('*')
.max(999, 'maxСharacters' + ' 1000'),
locale: Yup.string()
.required('*')
.max(999, 'maxСharacters' + ' 1000')
})
)
.required('Translations Required')
})
)
})
对于此数据对象:
[{"id":"","activitiId":"1","pictureGood":[],"pictures":[],"translations":[{"generalDesc":"test","descGood":"test","descBad":"test","locale":"IT"},"generalDesc":"test","descGood":"test","descBad":"test","locale":"EN"}]}]
但我只需要验证数组中的第一个元素,而不是所有元素。像这样的东西:.
translations: Yup.array()[0]
.of(
Yup.object().shape({
name: Yup.string().required('*'),
谢谢你的回答!
我也想这么做,我可以看到"索引";一旦我延长了我的";从";对象依据:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/49512……但我看不到索引。
因此,使用这种技术(我将在下面复制以获得完整答案(,我还成功地扩展了";选项";对象,然后扩展";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...
在这段代码中,您只需要检查数组的第一个元素
const YupSchema = (t: TFunction) =>
Yup.object().shape({
name: Yup.string()
.required('*')
.max(49, 'maxСharacters' + ' 50'),
areas: Yup.array().required('*'),
activities: Yup.array().of(
Yup.object().shape({
id: Yup.string().required('*'),
pictureGood: Yup.string().required('Required'),
pictureBad: Yup.string().required('Required'),
translations: Yup.array(
Yup.object({
name: Yup.string().required('*'),
desc: Yup.string().required('*').max(999, 'maxСharacters' + ' 1000'),
locale: Yup.string().required('*').max(999, 'maxСharacters' + ' 1000')
})
).test('check-first-element', VOYAGE_ERRORS.TRACTOR_RUNWAY, function () {
const { parent } = this;
const firstEle = parent[0];
if (firstEle.name === '' || firstEle.desc === '' || firstEle.locale === '') return false;
return true;
})
})
)
})