valibot: Custom error message of missing object entries changed in v1.0.0-beta.13

The error message returned for missing object entries has changed in v1.0.0-beta.13. Previously, the custom error message of the nested field was used. Now it uses the custom error message of the objectschema. With this issue we want to investigate if we should use the custom message of the nested field instead. Here is a playground and here is a code example:

import * as v from 'valibot';

const Schema = v.object({
  field: v.string('My custom error'), // This error message if "ignored"
});

const result = v.safeParse(Schema, {});

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 8
  • Comments: 30 (18 by maintainers)

Most upvoted comments

I am still investigating this issue. Please provide a 👍 or 👎 if the following workaround is an option for you. I only ask because I am currently investigating several changes to the current behavior, but they all have other drawbacks.

A lot of cases where you might want to set a specific custom message for a missing object property is when working with forms. The reason for this is that you may not have control over how untouched but required form fields are handled. Some form libraries don’t initialize them, resulting in a missing object property when representing the form state as an object.

A workaround could be to set the form field as optional in your Valibot schema, but provide an initial value, for example an empty string, as the default value to be used as input to the schema whenever the actual object property is missing or undefined. Now you can use a validation action like nonEmpty to return the same custom error message regardless of whether the property is missing, undefined, or an empty string. Feel free to test the following code example in this playground.

import * as v from 'valibot';

const Schema = v.object({
  email: v.pipe(
    v.optional(v.string(), ''), // <- Empty string as default value
    v.nonEmpty('Please enter your email.'),
    v.email('The email is badly formatted.'),
  ),
});

This is a horrible change in behavior. Before you could easily customize the error message for missing keys by passing a message to the field that is missing. Wrapping it in optional even though it is semantically required is extremely unintuitive.

Before:

v.object({ file: v.file("Select a file") });

After:

v.object({
  file: v.pipe(
    v.optional(v.file(), () => undefined),
    v.file("Select a file"),
  ),
});

i prefer the old behavior, i think most agree with me

For now, I think it is best to keep the current behavior as it is objectively more correct. If you run into this problem when building forms, I recommend specifying the initial form field values as defaults, so that your form library will always provide a value when running schema validation. Optionally, you can use one of the few workarounds described above.

Hi, I use valibot with a vue js, a key can be missing , but required , that why optional directive is’nt appropriate , a custom message is more suitable

Yes it is. Your problem is that your form library sends an empty string into the schema. The fix is to mark an empty string as a valid input with v.literal('').

v.optional(
  v.union([v.literal(''), v.pipe(v.string(), v.email())])
);

You can also abstract it with a small custom function:

import * as v from 'valibot';

function optionalInput<TSchema extends v.GenericSchema>(schema: TSchema) {
  return v.optional(v.union([v.literal(''), schema]));
}

const Schema = v.object({
  email: optionalInput(v.pipe(v.string(), v.email())),
});

Here is a playground link to try it out.

General note: If this issue is a problem for you when creating forms with a form library, in most cases you can simply add default values to your form to fix it.

but this feels less cleaner, “hacky”

General note: If this issue is a problem for you when creating forms with a form library, in most cases you can simply add default values to your form to fix it.

Here is a Valibot schema with a similar behavior. You can try it out in this playground.

I know this code example is a bit verbose, but we have to keep in mind that Zod does not distinguish between missing and existing but undefined object entries, which can lead to bugs in edge cases. This is exactly what we “fixed” in v1.0.0-beta.13, which is the reason for this discussion. 😐

import * as v from 'valibot';

const Schema = v.object({
  name: v.pipe(
    v.optional(v.string('The name should be string.'), () => undefined),
    v.string('Please let me know your name.'),
  ),
  birth_year: v.optional(v.number()),
});

Also keep in mind that Valibot allows you to read the actual input when generating an error message.

Without the new and more accurate validation behavior, this would behave almost exactly like your Zod example.

import * as v from 'valibot';

const Schema = v.object({
  name: v.string(({ input }) =>
    input ? 'The name should be string.' : 'Please let me know your name.'
  ),
});

Thanks @filipw01! Here is a slightly modified version where you can pass the schema without a function. You can try it out in our playground.

import * as v from 'valibot';

function required<TSchema extends v.GenericSchema<unknown>>(
  schema: TSchema,
  message?: v.ErrorMessage<v.InferIssue<TSchema>>,
) {
  const outputSchema = v.pipe(
    v.optional(schema, () => undefined),
    schema,
  );
  if (message) {
    // @ts-expect-error
    return v.message(outputSchema, message);
  }
  return outputSchema;
}

const Schema = v.object({
  email: required(v.string()),
  password: required(v.string(), 'With custom error message'),
});

I think the new and current implementation should be kept. We should figure out how to let users customize the error message for each missing key in the object. In the last code block of your last message, the users won’t be able to customize the “missing key” messages, as any custom message inside an entry’s schema would indicate “the input has the key and validation failed” instead of “the input did not contain the key”. Maybe there are cases where the author of the schema wants to provide a different message for the “missing key” and “validation failed” cases easily. What if we add a way to customize each “missing key” error message like shown in the example below?

import * as v from 'valibot';

const Schema = v.object({
  key1: [
    v.pipe(
      v.string('`key1` should be a string'),
      v.nonEmpty('`key1` cannot be empty'),
    ),
    '`key1` is required',
  ],
  key2: [
    v.pipe(
      v.string('`key2` should be a string'),
      v.nonEmpty('`key2` cannot be empty'),
    ),
    '`key2` is required',
  ],
  // If `key3` is missing, it will use object's error message
  key3: v.number('`key3` should be a number')
});

What an insane change, can it be reverted or placed under a flag, next to abortEarly and rest?

Using such hacks and wrappers is just madness. Additionally, object message is shown if field is missing 🤯

const schema = object({
  name: string('Name must be a string'),
  surname: string('Surname must be a string')
}, 'wtf...')

const { issues, output, success } = safeParse(schema, {})

flatten(issues)

result:

{ nested: { name: [ 'wtf...' ], surname: [ 'wtf...' ] } }

It’s not ideal, but for anybody looking for some helper function

const required = <T extends v.GenericSchema<unknown>>(
  schema: (error?: string) => T,
  error?: string
) => {
  return v.pipe(
    v.optional(schema(error), () => undefined),
    schema(error)
  ) as unknown as T
}

example usage

const schema1 = v.object({ prop: required(err => v.string(err), 'Your error message') })

const schema2 = v.object({ prop: required(err => v.array(v.string(), err), 'Your error message') })

I would recommend to take a look at /library/CHANGELOG.md or the release notes. But the change around objects and optional properties is probably the only bigger user facing breaking change. Feel free to join our Discord. We are happy to support you there.

Is your idea that required or nonUndefined will convert a missing object property to undefined and pass it to its nested schema?

No, my comment was solely about the readability of the code rather than the implementation. I don’t know if it’s possible to resolve this issue while still maintaining readability but thought I’d mention it.

If I’m a developer who is new to valibot then v.optional(v.string(), ''), // <- Empty string as default value makes it look like the property is optional rather than the actual effect of setting the default value to an empty string. It works but it’s not very readable.

EDIT: Having read https://valibot.dev/guides/mental-model/ I see this is likely not possible. ~Perhaps a more readable solution would be to add another validation that would check for undefined, e.g. v.required("Email is required") or v.notUndefined("Email is required") if input is undefined then display error “x is required”.~

Thanks for the great library by the way, it’s awesome 😃

> import * as v from 'valibot';
> 
> const Schema = v.object({
>   email: v.pipe(
>     v.optional(v.string(), ''), // <- Empty string as default value
>     v.nonEmpty('Please enter your email.'),
>     v.email('The email is badly formatted.'),
>   ),
> });

This works nicely but I find the use of v.optional to not be very readable/clear. It indicates to the reader that this property is now optional. I realize it may not fit correctly with the rest of the API design but a better option for readability would be v.required("Email is required"), or v.nonUndefined("Email is required").

I will look again at ways to get the best of both worlds. I have an idea in mind. I will get back to all of you here as soon as possible.