zod icon indicating copy to clipboard operation
zod copied to clipboard

Friendly Error Messages

Open stockson opened this issue 1 year ago • 3 comments

Is there a way to get a generic string or array of strings that I can pass back to an end user? With flatten and format it looks like I'd need to iterate through properties and arrays to try to create a message, and even then it wouldn't be very friendly. Writing custom messages feels a little redundant, and wouldn't be as helpful about communicating which validation on a property actually failed. Thanks for your help!

stockson avatar Aug 01 '22 22:08 stockson

Zod is very unopinionated about this stuff. It gives you all the information it can and lets you use whatever mechanism you like for displaying those to the end user. I'm certainly on board with trying to provide some default mechanism for simplifying this but I'm having a hard time imagining it currently. Perhaps you could flesh out this proposal so there's something more concrete to discuss?

colinhacks avatar Sep 06 '22 06:09 colinhacks

Had the same problem, I use zod-error, even the defaults provide a usefull message:

"Code: invalid_type ~ Path: response.action ~ Message: Required | Code: custom ~ Path: response.colour ~ Message: Invalid input"

TheEvilCoder42 avatar Sep 11 '22 19:09 TheEvilCoder42

Thanks for the feedback. That object response is great in terms of providing specific details to a developer, and zod-error is a nice alternative for quickly concatenating it.

My hope was to be able to quickly strap zod onto a generic form that a non-tech person was filling out and could easily understand, or even just to give quick hints to another developer violating the parameter constraints for an API.

For example a contact form on a website:

{
  first_name: string().min(2),
  work_email: string().email(),
  birthday: date().min( new Date() ),
  work: {
    state: enum([ "MA", "CA", "TX" ]),
    years_of_experience: number().int().positive()
  }
}

Then a list of friendly violated messages like,

[
  "first_name can't be blank",
  "first_name must be at least two characters long",
  "work_email must be a valid email address",
  "birthday must be a date",
  "birthday must be later than 9/13/2022",
  "work.state must be one of the following: MA, CA, TX",
  "work.years_of_experience must be an integer",
  "work.years_of_experience must be a positive number"
]

Maybe even a formatting config/functions for properties ex:

{
  showParentProperties: true|false // "work.state" vs "state",
  formatMessage: ( val ) => val.replace( /_/g, " " ), // "first_name" to "first name"
  // or
  formatPropertyName: ''
}

What do you think?

stockson avatar Sep 13 '22 16:09 stockson

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 Nov 13 '22 08:11 stale[bot]