[PROPOSAL] Custom validation message formatter
sendyhalim opened this issue · 1 comments
sendyhalim commented
There are needs where we want to format validation message parameters, for example: I'm validating a salary input with minValue
.
Current behaviour:
const rules = {
salary: ['minValue:1000000']
};
const input = {
salary: 999999
};
satpam.validate(rules, input); // "Salary must be greater than or equal to 1000000."
The salary
validation message is "Salary must be greater than or equal to 1000000."
, notice the 1000000, the ideal situation is to have some kind of parameter formatter so we can customise the rendering of validation parameters .
Desired behaviour:
const locale = 'id';
const rules = {
salary: ['minValue:1000000']
};
const input = {
salary: 999999
};
const options = {
// The formatter will be run before passing validation message
// parameters into template string.
// https://github.com/cermati/satpam/blob/master/src/validators/min-value.js#L18
validationMessageParamsFormatter: ({ propertyName, propertyValue, inputObj, violatedRule }) => {
// For simplicity's sake, we're going to only use `minValue` rule, it has 1 param.
const formattedParam = currencyFormatter.format(violatedRule.params[0]);
return {
propertyName: propertyNameByLocale[locale], // You can also do translation here
ruleParams: [formattedParam]
};
},
// The formatted validation message parameters will be feed into template string which
// could have further customisation https://github.com/cermati/satpam/issues/103
validationMessagePack: ....
}
satpam.validate(rules, input, options); // "Pendapatan harus lebih besar dari IDR 1.000.000."
sendyhalim commented
Development done 🏖️