form: Add a way to display only one error for a field

Describe the bug

Currently we return field.state.meta.touchedErrors ValidationError[] as a string by concataining the different errors of a field with commas.

It would be great to be able to display only one error.

e.g:

         validators={{
            onChange: v.string([
              v.minLength(1, t(i18n)`This field is mandatory`),
              v.custom(isDateStringValid, t(i18n)`The birth date format is incorrect`),
              v.custom(isDateStringOver18, t(i18n)`You have to be at least 18 years`),
            ]),
          }}

These valibot validators will end up on showing all three errors just by typing a letter and deleting it. Imo, this is not a good UX.

I would expect some kind of priority in the error messages, thus only displaying the first validation to return an error.

Your minimal, reproducible example

https://github.com/TanStack/form/

Steps to reproduce

     validators={{
        onChange: v.string([
          v.minLength(1, t(i18n)`This field is mandatory`),
          v.custom(isDateStringValid, t(i18n)`The birth date format is incorrect`),
          v.custom(isDateStringOver18, t(i18n)`You have to be at least 18 years`),
        ]),
      }}

Expected behavior

More control over the errors display

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

macOS

TanStack Form adapter

react-form

TanStack Form version

0.19.0

TypeScript version

No response

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

Maaaybe this? (Sorry, it’s not very clean and I’m not sure at all)

import { safeParse, safeParseAsync } from 'valibot'
import type { BaseIssue, BaseSchema, BaseSchemaAsync } from 'valibot'
import type { Validator } from '@tanstack/form-core'

type Params = {
  errorMap?: (
    errors: [BaseIssue<unknown>, ...BaseIssue<unknown>[]],
  ) => BaseIssue<unknown>
}
type validateValue = { value: unknown }
type validateFn =
  | BaseSchema<unknown, unknown, BaseIssue<unknown>>
  | BaseSchemaAsync<unknown, unknown, BaseIssue<unknown>>

export const valibotValidator = ((params: Params = {}) => {
  return {
    validate({ value }: validateValue, fn: validateFn) {
      if (fn.async) return
      const result = safeParse(fn, value)
      if (result.success) return
      if (params.errorMap) {
        return params.errorMap(result.issues)
      }
      return result.issues.map((i) => i.message).join(', ')
    },
    async validateAsync({ value }: validateValue, fn: validateFn) {
      const result = await safeParseAsync(fn, value)
      if (result.success) return
      if (params.errorMap) {
        return params.errorMap(result.issues)
      }
      return result.issues.map((i) => i.message).join(', ')
    },
  }
}) as Validator<
  unknown,
  | BaseSchema<unknown, unknown, BaseIssue<unknown>>
  | BaseSchemaAsync<unknown, unknown, BaseIssue<unknown>>
> &
  ((
    params: Params,
  ) => Validator<
    unknown,
    | BaseSchema<unknown, unknown, BaseIssue<unknown>>
    | BaseSchemaAsync<unknown, unknown, BaseIssue<unknown>>
  >)

I’m sorry for my slow understanding.

The current type of validatorAdapter:

export type Validator<Type, Fn = unknown> = () => {
    validate(options: {
        value: Type;
    }, fn: Fn): ValidationError;
    validateAsync(options: {
        value: Type;
    }, fn: Fn): Promise<ValidationError>;
};

But if i use valibotValidator like this with @t-rosa 's code

 validatorAdapter: valibotValidator({ errorMap: (errors) => errors[0] }),

valibotValidator return just

 {
    validate({ value }: validateValue, fn: validateFn) {
      if (fn.async) return
      const result = safeParse(fn, value)
      if (result.success) return
      if (params.errorMap) {
        return params.errorMap(result.issues)
      }
      return result.issues.map((i) => i.message).join(', ')
    },
    async validateAsync({ value }: validateValue, fn: validateFn) {
      const result = await safeParseAsync(fn, value)
      if (result.success) return
      if (params.errorMap) {
        return params.errorMap(result.issues)
      }
      return result.issues.map((i) => i.message).join(', ')
    },
  }

Not function, just object.

So the types don’t match. How can this be solved?

Yes, you’re right.

I think we should use the first version, even if it’s a mini breaking change. as crutchcorn said it shouldn’t be a problem 😃

So this one maybe the best option:

import { safeParse, safeParseAsync } from 'valibot'
import type { BaseIssue, BaseSchema, BaseSchemaAsync } from 'valibot'
import type { Validator } from '@tanstack/form-core'

type Params = {
  errorMap?: (
    errors: [BaseIssue<unknown>, ...BaseIssue<unknown>[]],
  ) => BaseIssue<unknown>
}

export const valibotValidator = (params: Params = {}) =>
  (() => {
    return {
      validate({ value }, fn) {
        if (fn.async) return
        const result = safeParse(fn, value)
        if (result.success) return
        if (params.errorMap) {
          return params.errorMap(result.issues)
        }
        return result.issues.map((i) => i.message).join(', ')
      },
      async validateAsync({ value }, fn) {
        const result = await safeParseAsync(fn, value)
        if (result.success) return
        if (params.errorMap) {
          return params.errorMap(result.issues)
        }
        return result.issues.map((i) => i.message).join(', ')
      },
    }
  }) as Validator<
    unknown,
    | BaseSchema<unknown, unknown, BaseIssue<unknown>>
    | BaseSchemaAsync<unknown, unknown, BaseIssue<unknown>>
  >

I quickly passed by here and was seeing something like this, it probably doesn’t work and I don’t have time to test/research in depth but maybe it will help:

import { safeParse, safeParseAsync } from 'valibot'
import type { BaseIssue, BaseSchema, BaseSchemaAsync } from 'valibot'
import type { Validator } from '@tanstack/form-core'

type Params = {
  errorMap?: (
    errors: [BaseIssue<unknown>, ...BaseIssue<unknown>[]],
  ) => BaseIssue<unknown>
}

export const valibotValidator = (params: Params) =>
  (() => {
    return {
      validate({ value }, fn) {
        if (fn.async) return
        const result = safeParse(fn, value)
        if (result.success) return
        if (params.errorMap) {
          return params.errorMap(result.issues)
        }
        return result.issues.map((i) => i.message).join(', ')
      },
      async validateAsync({ value }, fn) {
        const result = await safeParseAsync(fn, value)
        if (result.success) return
        if (params.errorMap) {
          return params.errorMap(result.issues)
        }
        return result.issues.map((i) => i.message).join(', ')
      },
    }
  }) as Validator<
    unknown,
    | BaseSchema<unknown, unknown, BaseIssue<unknown>>
    | BaseSchemaAsync<unknown, unknown, BaseIssue<unknown>>
  >