jquense / yup

Dead simple Object schema validation
MIT License
22.74k stars 927 forks source link

Way to include HTML inside validation error message? #1772

Closed LucyMac closed 2 years ago

LucyMac commented 2 years ago

I have a form for users to book an appointment, including a "choose a date" field.

If their chosen date is not valid (for whatever reason), I want to direct users to fill out a survey and let us know about their specific needs.

I therefore want the error message to include a link: example: Sorry we're fully booked. For other options, please contact us here where "here" is a hyperlink to an external survey.

Is there a way to insert HTML inside the error message ❓

In my case <a href="www.external-survey.com">here</a>

Stack: I'm using React with Formik and Yup for validation.

I couldn't find any reference to this anywhere. Any tips welcome! 🙏🏼

Thanks

jquense commented 2 years ago

You can put whatever you want in a message, but it's up to you to render it correctly for a user.

ghost commented 2 years ago

Hey @LucyMac

As mentioned above, this is not really a Yup or a Formik related thing, but rather just a React thing. I whipped up a quick sandbox of how you can accomplish this with dangerouslySetInnerHTML.

https://codesandbox.io/s/formik-html-in-error-example-1w4vuj?file=/src/App.js

I would recommend against hardcoding your URLs into your schema because that can change for a number of reasons. Some alternative approaches would be to append the URL to the error message, or to render a completely custom bit of JSX based on the error being present rather than just displaying the error message as delivered by Yup.

Happy hunting!

LucyMac commented 2 years ago

Thanks very much for the sandbox @jodylecompte and @jquense 🙏🏼

shob101 commented 5 months ago

Hey @LucyMac I am facing a similar kind of problem as you have discussed above and I am unable to find any reference for this problem too. I was trying to access the sandbox mentioned above but I think it's deleted now.

I'll be very glad if you can share any tips or guidance for the same. Thanking you in advance mate.

CC: @jodylecompte @jquense

jodylecompte commented 5 months ago

@shob101 I can't remember exactly what I put in that sandbox, or why it's gone for that matter.

I'm also not really sure why I recommended dangerouslySetInnerHtml. I think a better course of action would be to conditioning render the custom error message in the event the Yup error object is what you expect. If there are not multiple error states with different output, you could also just check if the form is invalid.