ember-validators icon indicating copy to clipboard operation
ember-validators copied to clipboard

Allow for partial application of the message context

Open xcambar opened this issue 8 years ago • 2 comments

This PR allows, with a backward compatible modification, to let the developers partially apply a context to a message.

This is very useful for instance when extending the messages provided by ember-validations to reuse messageFor to do the extension/replacement instead of doing a .replace(...) manually, which might break eventually...

Down to earth example:

  • we were working with wrongDateFormat ("{description} must be in the format of {format}")
  • The format used was L (using the moment terminology)
  • We wanted the localised version of L ("MM/DD/YYYY" in en_US and "JJ/MM/AAAA" in fr_FR) in the message
  • We had to write this PR to allow for:
return this.formatPartialMessage(pattern, { format: localisedString});
// return value is "{description} must be in the format of JJ/MM/AAAA"

What do you think?

xcambar avatar Aug 19 '17 23:08 xcambar

@xcambar not sure I follow you here. Where is this partial message being created? Why is it needed? and what are you doing with it after?

offirgolan avatar Aug 25 '17 22:08 offirgolan

Here's what I can achieve with this PR:

    validator('date', {
      precision: 'day',
      message: function(err, input, validator) {
        let localizedFormat = moment().localeData().longDateFormat(validator.get('format')); // => DD/MM/YYYY because lang == 'fr_FR'
        let translatedFormat = t(localizedFormat); // => JJ/MM/AAAA in french
        return validatorsMessages.formatPartialMessage(wrongDateFormat, { format: localizedFormat });
        // => {description} must be in the format of JJ/MM/AAAA
      },
      format: 'L'
    })

With the current master of ember-validators, I didn't succeed in having the error message to be This field must be in the format of JJ/MM/AAAA. If you can provide some guidance towards this with a simple solution, then yes, this PR may be superfluous.

A couple of notes:

  • yes, language must be english, and yes, the dates must be in french
  • I need to have the message return {description} must... instead of directly returning This field must...

xcambar avatar Aug 26 '17 11:08 xcambar