validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

feat: access of input value on template string for error messages

Open agSant01 opened this issue 3 years ago • 0 comments

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.

agSant01 avatar Apr 01 '21 04:04 agSant01