valibot: Add an example for handling ValiError errors

I would like to see how to correctly handle the ValiError when parsing a schema. In a type-safe manner. For example in this login form handling demo:


const LoginSchema = v.object({
  email: v.pipe(v.string(), v.nonEmpty(), v.email() ),
  password: v.pipe(v.string(), v.nonEmpty(), v.minLength(6) ),
});

const [formData, setFormData] = useState<LoginSchemaType>({
    email: '',
    password: '',
  });
const [formErrors, setFormErrors] = useState<`What HERE?`>();
  
  
const handleLogin = async () => {
    setFormErrors({});

    try {
      v.parse(LoginSchema, formData)
      await loginMutation(formData)
    } catch (error) {
      if (error instanceof v.ValiError && error.issues) {
        const flatIssues = v.flatten<typeof LoginSchema>(error?.issues)
        const newErrors = {};

        Object.entries(flatIssues.nested).forEach(([key, value]) => {
          newErrors[key] = value[0]
        })

        setFormErrors(newErrors);
      } else {
          console.error(error)
      }
    }
  };

I am getting a crazy type issue on Object.entries(flatIssues.nested) at this point. More importantly, how to type the formErrors variables? I would love to see the team’s approach to this.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

Okay, I ended up doing something like this. And it works well enough.

const someSchema = v.object({
// ... definition
})

type MySchemaType = typeof someSchema
type FormErrorKey = v.IssueDotPath<MySchemaType>

const formErrors: Partial<Record<FormErrorKey, string>> = {};

const handleSubmit = async () => {
    try {
      // validate form data
      v.parse(someSchema, { ...formData })

      // send data to API
      await callAsyncApi({ ...formData });
      
    } catch (error) {
      if (v.isValiError<MySchemaType>(error)) {
        const flatIssues = v.flatten<MySchemaType>(error.issues)

        for (const key in flatIssues.nested) {
          formErrors[key as FormErrorKey] = flatIssues.nested[key as FormErrorKey]![0];   // I hope that this line could be improved in the future
        }

        if(Object.keys(formErrors).length) {
           renderErrorMessages(formErrors)
        }

      } else {
        console.error("Edit Link Error", error)
        throw error
      }
    }
  };

I hope this could be useful to someone