kaliberjs / forms

Forms for React
MIT License
4 stars 0 forks source link

Checkbox and showError on blur #14

Closed JoostKiens closed 4 years ago

JoostKiens commented 4 years ago

Is it possible to show a validation error of a checkbox on blur?

See the following test case:

import { useBooleanFormField, useForm } from '@kaliber/forms'

function needsToBeChecked(x) {
  return x !== true && { id: 'needsToBeChecked' }
}

export function Form() {
  const { form: { fields }, submit } = useForm({
    initialValues: { tos: false },
    fields: { tos: needsToBeChecked },
    onSubmit: x => { console.log(x) },
  })

  return (
    <form onSubmit={submit}>
      <FormCheckbox label='I agree with the Terms of Service' field={fields.tos} />
      <button type='submit'>Submit</button>
    </form>
  )
}
function FormCheckbox({ label, field }) {
  const { name, state, eventHandlers } = useBooleanFormField(field)
  const { showError, error, value } = state
  console.log(showError, error)
  return (
    <>
      <div>
        <label htmlFor={name}>{label}</label>
        <input id={name} type='checkbox' checked={value || false} {...{ name }} {...eventHandlers} />
      </div>
      {showError && <p>{error.id}</p>}
    </>
  )
}

I would expect the error to be shown as soon as we uncheck the checkbox. However,showError is always false until we submit the form.

EECOLOR commented 4 years ago

I have added an example that shows this behavior. Not sure what causes the problem in your test case.

JoostKiens commented 4 years ago

Thanks for the example!

Not sure what causes the problem in your test case.

After investigating a bit, I found out it seems to be an issue in Firefox & Safari. This is also the case with your example. In Chrome it works as expected.

EECOLOR commented 4 years ago

Let me know if you find a workaround

EECOLOR commented 4 years ago

Seems we are not alone: https://github.com/react-hook-form/react-hook-form/issues/1079

JoostKiens commented 4 years ago

Looks like browser bugs. Reports going back to 2007 😳.

Seems I'll just have to accept that this is the world we live in. Closing, thanks for your time 👍

https://bugs.webkit.org/show_bug.cgi?id=13724 https://bugzilla.mozilla.org/show_bug.cgi?id=756028

EECOLOR commented 4 years ago

If we feel this is really important we could write a custom onBlur.