Skip to content

Support for translation options #632

@rreckonerr

Description

@rreckonerr

Hi! First of all want to thank you for a great validation library!

Currently, I'm in a process of migrating my ember app to your validations library and I'm struggling with error keys emitted by custom enforce methods.

I'm migrating from an older validation library so I have to support their translations API. It includes translation keys and passed translation options. It seemed like a good idea to extend enforce with methods that'll match the previous translations, but I can't find a way of providing additional data to send along with the transition key.

Let's say I have an ICU translation defined as follows:

{
  "errors": {
    "greater-than-or-equal-to": "At least {gte} options must be selected"
  }
}

And I'd like to return an object with additional data as a result message message

const greaterThanOrEquals = (received, floor) => {
  return {
    pass: received >= floor,
    message: () => ({ key: "errors.greater-than-or-equal-to", gte: floor }), // something like this
  };
};

Currently, I'm translating error messages from enforce like this

  get errorMessages() {
    return Object.entries(this.validator.getErrors()).map(
      ([fieldName, [errorKey]]) =>
        this.intl.t(errorKey, {
          description: fieldName,
        })
    );
  }

but unfortunately, it doesn't work if I try to return an object as the enforce result message.

Do you have any idea how to work around this? I can provide custom enforce methods with additional context and return translated message as a result, but there are few problems with this approach

  1. There's no access to the name of the field from within enforce method (e.g. test("Field Name", ....))
  2. If I'll provide additional data to the enforcers and vest won't be that much framework-agnostic anymore

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions