diff --git a/docs/guides/form-errors.md b/docs/guides/form-errors.md new file mode 100644 index 0000000000..e1b6bfa98c --- /dev/null +++ b/docs/guides/form-errors.md @@ -0,0 +1,136 @@ +--- +title: Form Errors +category: Guides +order: 7 +--- + +# Adding Error Messages to Form Components + +InstUI offers a range of form elements and all of them have a similar API to handle error/hint/success messages. These components use the `messages` prop with the following type definition: + +```ts +--- +type: code +--- +type FormMessages = { + type: + | 'newError' + | 'error' + | 'hint' + | 'success' + | 'screenreader-only' + text: React.ReactNode +}[] +``` + +So a basic example would look something like this: + +```ts +--- +type: example +--- +const PasswordExample = () => { + const [password, setPassword] = useState('') + const messages = password.length < 6 + ? [{type: 'newError', text: 'Password have to be at least 6 characters long!'}] + : [] + return ( + { setPassword(value) }} + /> + ) +} + +render() +``` + +However you might have noticed from the type definition that a message can be `error` and `newError` type. This is due to compatibility reasons. `error` is the older type and does not meet accessibility requirements, `newError` (hance the name) is the newer and more accessible format. + +We wanted to allow users to start using the new format without making it mandatory, but after the introductory period `newError` will be deprecated and `error` type will be changed to look and behave the same way. + +With this update we also introduced the "required asterisk" which will display an `*` character next to field labels that are required. This update is not opt-in and will apply to **all** InstUI form components so if you we relying on a custom solution for this feature before, you need to remove that to avoid having double asterisks. + +Here are examples with different form components: + +```ts +--- +type: example +--- +const Example = () => { + const [showError, setShowError] = useState(true) + const [showNewError, setShowNewError] = useState(true) + const [showLongError, setShowLongError] = useState(false) + const [isRequired, setIsRequired] = useState(true) + + const messages = showError + ? [{type: showNewError ? 'newError' : 'error', text: showLongError ? 'Long error. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos voluptas, esse commodi eos facilis voluptatibus harum exercitationem. Et magni est consectetur, eveniet veniam unde! Molestiae labore libero sapiente ad ratione.' : 'Short error message'}] + : [] + + const handleSettingsChange = (v) => { + setShowError(v.includes('showError')) + setShowNewError(v.includes('showNewError')) + setShowLongError(v.includes('showLongError')) + setIsRequired(v.includes('isRequired')) + } + + return ( +
+ + + + + + +
+ + + + + +