TanStackT
TanStack6mo ago
4 replies
popular-magenta

Force Blur for Manual Validation (Solved)

Maybe I'm missing something simple, but I'm struggling with handling validation properly in the forms.

I need to have it handle so that it only shows the error if the field has been blurred, so that when someone types "t" the entire form just doesn't show errors onChange. Each field will only show the errors when they have been blurred,

However, I need to then have the ability to show the errors if the user clicks on the submit button before its valid (my submit will call an onClick instead of submit if the form is not valid). But I don't know how to remove the isBlurred part.

This seems like a super common case, so maybe its because I only work on this at 11pm lmao, but surely there are lots of people who don't want errors until submission / blur, and then want those errors to be fixed on change once they appear.

Context:
  const { state, handleBlur, handleChange } = useFieldContext<string | number | readonly string[] | undefined>()
  const {
    value,
    meta: { errors, isDirty, isBlurred },
  } = state
  /*****  RENDER  *****/
  return (
    <Input
      {...props}
      value={value}
      onChange={(e) => handleChange(e.target.value)}
      onBlur={handleBlur}
      error={isDirty && isBlurred && errors?.[0]?.message}
    />
  )

<form.Subscribe selector={({ canSubmit, isSubmitting }) => ({ canSubmit, isSubmitting })}>
      {({ canSubmit, isSubmitting }) => (
        <Button
          type={canSubmit ? "submit" : "button"}
          disabled={isSubmitting}
          onClick={() => !canSubmit && form.validateAllFields("change")}
          color="sky"
        >
          {label ?? "Submit"}
        </Button>
      )}
    </form.Subscribe>


This is my input and button. validateAllFields won't work (as in show the errors) because of the "isBlurred" and possible also the isDirty. But i need these
Was this page helpful?