-
Notifications
You must be signed in to change notification settings - Fork 1
[Proposal] Support Dynamic Copy for ngMessages #1
Description
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.';
}
}]
]
}
}