validatorjs
validatorjs copied to clipboard
feat: access of input value on template string for error messages
Feat Error Template Message
Overview
The goal of this PR is to allow access of the input value on the error messages template strings via a :inputValue
keyword.
Use Case
A use case where user is making upload of an excel file with 100+ rows, and the validation of those fields throw an validation error just saying to the user that an error occurred is not very helpful.
It would be better to return the actual values(s) that are invalid so the user can find the values and perform the fixes.
const validation = new Validator(
data,
{
array: 'required|array',
'array.*.postalCode': 'required|postal_code',
// rest of validation schema...
},
{
'postal_code.array.*.postalCode': "The postal code ':inputValue' is not valid.",
}
);
// output -> "The postal code '0O987' is not valid." | Second character is a letter 'O'
Proposed implementation
Modify the Messages._replacePlaceholders(rule, template, data)
to add the rule.inputValue
to the data object. By doing this it will not collide with the existing implementation of :value
templater for the custom replacements.
Object as input value
The default string representation of an {}
is [object Object]. In order to make it more readable the behavior of the replacement will be to replace it for [Object] only.
PS. It was also considered the option {...}
. Open to feedback on this.
Updated README.md
Updated the README to reflect the newly added feature.