vazco / uniforms

A React library for building forms from any schema.
https://uniforms.tools
MIT License
1.94k stars 239 forks source link

Schema validation does not work if AutoForm as onValidate #1257

Closed chiester closed 1 year ago

chiester commented 1 year ago

Using AutoForm with JSON Schema, if AutoForm has onValidate property, schema validation does not work. Remove the onValidate and schema validation works. Remove it and it it stops working. The test onValidate is simply returning null.

Reproduction repository, https://github.com/chiester/uniforms-onvalidate-bug CodeSandbox: https://codesandbox.io/p/github/chiester/uniforms-onvalidate-bug

chiester commented 1 year ago

It appears that if onValidate returns the error, it works. However, the documentation at https://uniforms.tools/docs/api-forms/#props-1 seems to suggest returning null to skip async validation, so this is misleading. Also, in previous versions, I returned null from onValidate and had no problem so this seems to have changed in recent versions.

radekmie commented 1 year ago

Hi @chiester. There's a misunderstanding regarding how the onValidate works. This function receives both the model as well as the validation error and decides what the resulting error is.

Returning null at all times simply disabled validation, as whenever the form validates, it passes the validation result through onValidate and it says "none" (null means no error).

In your case, if you'd like to have some additional async validation, then it should look like this instead:

async function onValidate(model, error) {
  // If there's any error from the schema, leave it.
  if (error) {
    return error;
  }

  // If the schema passed, validate using our custom logic.
  return await validate(model);
}

I hope it's clear now.

radekmie commented 1 year ago

No response so far, so I'm closing. Feel free to comment further!