zod icon indicating copy to clipboard operation
zod copied to clipboard

Allow setting a label and pass it through to error map

Open Svish opened this issue 2 years ago • 4 comments

Don't remember the exact rule, but I believe there is a WCAG requirement that error messages should refer to the name of the field it's about. I.e. Field is required is less good than for example "First name" is required.

Would be great if we could add a label to our schema, which would be used in the default error map, and be made available in custom error map functions.

const mySchema = z.object({
  firstName: z.string({ label: 'First name' }),
  dateOfBirth: z.date({ label: 'Date of birth' }),
})

I see there's already a description, but it's not documented anywhere, so not sure what that is for. If it's actually for a label, then I guess this would be solved simply by exposing that description in the error map somehow. Maybe it could come as part of the ErrorMapCtx object?

screenshot

Svish avatar Jun 15 '22 10:06 Svish

I had a stab at this, not sure it's necessarily right or in the right place though given that I have attached the info to issue as opposed to context...

Find myself in need of this functionality too 👍

Screenshot 2022-07-04 at 15 27 33

Notice the addition of "type" and "description" alongside how I have interpolated the description into the error message, the gist below shows how I achieved it. Pretty nasty implementation just to show in principle how error messages can more closely resemble how Yup handles them.

https://gist.github.com/WazzaJB/2eca3df3369c91317edaad3ed96862a6

WazzaJB avatar Jul 04 '22 14:07 WazzaJB

Similar issues and conversations include #1154 #901 #456

WazzaJB avatar Jul 04 '22 14:07 WazzaJB

any roadmap to implement this? in yup they have label method to override the field name. this comes in handy when validation an object, so we can rename each field with human readable text not object name.

hi-reeve avatar Jul 29 '22 07:07 hi-reeve

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 27 '22 10:09 stale[bot]