Reputation: 629
I have an Aurelia app and I am using the Aurelia validation tool for client-side validation. I want to use the validationMessages
dictionary to define a list of custom validation messages to use throughout my app using withMessageKey
like so:
import {validationMessages} from 'aurelia-validation';
validationMessages['customMessage1'] = `My first custom message`;
validationMessages['customMessage2'] = `My second custom message`;
And then when I set the validation rules on the class:
import { ValidationRules } from "aurelia-validation";
export class SampleObject {
text1;
text2;
constructor() {
ValidationRules
.ensure(a => a.text1)
.required()
.then().satisfies(x => x.trim() === x)
.withMessageKey('customMessage1')
.ensure(a => a.text2)
.satisfies( x => x.length > 5)
.withMessageKey('customMessage2')
.on(this);
}
};
The validation works, but the custom messages do not show up, the standard ones do. If I use withMessage('My first custom message')
for example instead, then it does work, but I want to keep all of my custom messages in one place for use throughout the app.
What am I doing wrong?
Upvotes: 2
Views: 541
Reputation: 629
Here is my solution:
I created a class which contains my custom messages in the constructor:
import { validationMessages } from 'aurelia-validation';
export class CustomValidationMessages {
constructor() {
validationMessages['customMessage1'] = `My first custom message`;
validationMessages['customMessage2'] = `My second custom message`;
}
}
Then, I inject it into my app.js
:
import { inject } from 'aurelia-framework';
import { CustomValidationMessages } from "resources/utils/validation-messages";
@inject( CustomValidationMessages )
export class App {
constructor() {
}
configureRouter(config, router) {
.....
}
}
And I am able to use customMessage1
and customMessage2
everywhere throughout my app. I'm not sure this is the best way to do this, but it works.
Upvotes: 1