jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

About setLocale and addMethod #2247

Open aarisfauji opened 2 months ago

aarisfauji commented 2 months ago

I am experiencing an issue when using setLocale and addMethod in Yup. After creating a custom method phone and setting the locale, the error message returned is not what I expected.

Code Used

const yup = require("yup");

yup.setLocale({
  mixed: {
    default: () => ({ key: "mixed.default" }),
    required: () => ({ key: "mixed.required" }),
    notType: () => ({ key: "mixed.notType" }),
  },
  string: {
    default: () => ({ key: "string.default" }),
    phone: () => ({ key: "string.phone" }),
  },
});

yup.addMethod(yup.string, "phone", function () {
  return this.test(function (value) {
    // Todo: regex phone
    return this.createError();
  });
});

let schema = yup.object().shape({
  name: yup.string().required().phone(),
});

try {
  schema.validateSync({ name: "test only" });
} catch (err) {
  messages = err.errors.map((err) => {
    console.info(err);
  });
  // TODO: do something (messages)
}

Issue

When I run the code above, the error message I receive is:

{ key: 'mixed.default' }

I expected to get the message:

{ key: 'string.phone' }

Expectations

I would like to understand why the error message generated does not match my expectations and how to fix it so that the string.phone error message appears when validation fails on the phone method.

Versions

Thank you for your help and clarification!

thany commented 1 month ago

The setLocale function only knows about the default keys, and ignores all others. If you use typescript, you can see this being enforced through typings as well.

This to me, is one of the great shortcomings of Yup. And you'll see that every example that shows how to fix this, is too simple: they assume you've already magiced up your translation from somewhere, to hardcode it into your schema. And I think we agree that translations, or translatable strings, do not belong in schemas.

So in short, good to report this. But I don't think this will realistically be fixed short term, if ever.

My workaround is to put these keys (e.g. 'string.phone') as the validation messages, and let your application pick them up as translation keys at the time of rendering the component that displays them. Downside is that it becomes quite annoying to have params together with your keys, and it requires a bit of extra pipework, but you might be able to make it work at least.

How exactly this workaround is piped together, completely depends on the framework (if any) of your choice.