Skip to content
This repository was archived by the owner on Feb 7, 2023. It is now read-only.
This repository was archived by the owner on Feb 7, 2023. It is now read-only.

[Proposal] Support Dynamic Copy for ngMessages #1

@darkobits

Description

@darkobits

Support Dynamic Copy for ngMessages

Use Case:

In an address form, a developer may be doing validation to check that a user's postal code is valid for the state/province they have selected. The developer would like to tailor the validation error message for the postal code field to say something like, "Please enter a valid zip code for California."

This requires that the ngMessage copy be dynamic.

Proposal:

Allow developers to pass either a string literal or a function when defining error messages:

vm.controls = {
  postalCode: {
    errors: [
      // Static error copy.
      ['required', 'This field is required.'],
      // Dynamic error copy.
      ['pattern', () => {
        const state = vm.addressForm.getModelValues().state;
        return `Please enter a valid postal code for ${state}.`;
      }]
    ]
  }
}

This approach would allow a developer to use any data in the context of the form's parent controller's closure to compute the copy for the error message. The downside, however, is that these definitions now become very tightly-coupled to the specific form in which they are being used; the error message function is making an assumption about control names in the form. This makes dynamic definitions less share-able and less reusable.

One way to combat this could be to ensure that these functions have fallbacks if their assumptions are false:

vm.controls = {
  postalCode: {
    errors: [
      // Static error copy.
      ['required', 'This field is required.'],
      // Dynamic error copy.
      ['pattern', () => {
        const state = vm.addressForm.getModelValues().state;
        
        if (state) {
          return `Please enter a valid postal code for ${state}.`;
        } else {
          // Form doesn't have a control named "state", or the
          // state control has a falsy model value. 
          return 'Please enter a valid postal code.';
        }
      }]
    ]
  }
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions