Add error to context with nested schemas using Zod validation

I have a Typescript application that is using Zod to validate data. The schema includes several schemas that have slightly different values with nested fields represented by other schemas as they can be reused in other places.

There is a nested object that when any object under a certain level will add an additional error to the Zod context. An example such as this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
a: {
b: { // d or e should both add another error
d: "1",
e: "3",
},
},
}
</code>
<code>{ a: { b: { // d or e should both add another error d: "1", e: "3", }, }, } </code>
{
  a: {
    b: { // d or e should both add another error
      d: "1",
      e: "3",
    },
  },
}

So, if d failed validation I want there to be the standard Zod validation error and a custom error added to the context as well. Reading it would seem as though I would want to use superRefine to do this. However, if I add superRefine it does not seem to trigger if the validation failure happens in a nested schema.

Code: https://github.com/rlperez/so-demo-zod

If I had a schema such as this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const BazSchema = z.string();
const BarSchema = z.object({
baz: BazSchema
});
const FooSchema = z.object({
bar: BarSchema
});
</code>
<code>const BazSchema = z.string(); const BarSchema = z.object({ baz: BazSchema }); const FooSchema = z.object({ bar: BarSchema }); </code>
const BazSchema = z.string();

const BarSchema = z.object({
  baz: BazSchema
});

const FooSchema = z.object({
  bar: BarSchema
});

When I call FooSchema.parse(obj) that fails for BazSchema does not trigger superRefine if it is written like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const FirstSuperRefinedFooSchema = FooSchema.superRefine((data, ctx) => {
if(!BarSchema.safeParse(data).success) {
ctx.addIssue({
code: 'custom',
message: 'first super refined custom message',
});
}
});
</code>
<code>const FirstSuperRefinedFooSchema = FooSchema.superRefine((data, ctx) => { if(!BarSchema.safeParse(data).success) { ctx.addIssue({ code: 'custom', message: 'first super refined custom message', }); } }); </code>
const FirstSuperRefinedFooSchema = FooSchema.superRefine((data, ctx) => {
  if(!BarSchema.safeParse(data).success) {
    ctx.addIssue({
      code: 'custom',
      message: 'first super refined custom message',
    });
  }
});

and is called like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> let parseResult = FooSchema.safeParse(wrongTypeBaz);
</code>
<code> let parseResult = FooSchema.safeParse(wrongTypeBaz); </code>
  let parseResult = FooSchema.safeParse(wrongTypeBaz);

Output

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>> [email protected] dev
> npx tsc -t 'es2017' && node ./src/main.js
stupid demo
FirstSuperRefinedFoo
mapping invalid_type
{"error":[{"code":"invalid_type","expected":"object","received":"undefined","path":["bar"],"message":"Required"}]}
</code>
<code>> [email protected] dev > npx tsc -t 'es2017' && node ./src/main.js stupid demo FirstSuperRefinedFoo mapping invalid_type {"error":[{"code":"invalid_type","expected":"object","received":"undefined","path":["bar"],"message":"Required"}]} </code>
> [email protected] dev
> npx tsc -t 'es2017' && node ./src/main.js

stupid demo

FirstSuperRefinedFoo
mapping invalid_type
{"error":[{"code":"invalid_type","expected":"object","received":"undefined","path":["bar"],"message":"Required"}]}

The expectation is that it would also have the custom error. I’ve added print statements to make sure it is not reaching superRefine. It’s as if it doesn’t raise the event any further than where it happened. I would need to manually add this to each schema? That seems like a lot of copy and paste across this schema to do that.

How does one do this?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật