validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

Custom attributes names not supported when using wildcard

Open oferrero opened this issue 3 years ago • 1 comments

The default implementation of the attributeFormatter receives the indexed attribute name. For example something like addresses.5.line_one. This key is then used to directly fetch a matching value from the attributeNames.

Similar to the rule definitions, the attribute names there should support wildcard values.

This way we can assign a custom attribute name to all items in a collection at once.

To get around it I had to implement a custom attribute formatter that replaces the .{number}. with .*. and then use that to lookup. the correct value from the attributeNames.

  validator.setAttributeNames(attributeNames)

  validator.setAttributeFormatter((attribute) => {

    // Replaces `.{number}.` with `.*.` to try to match to a custom attribute name
    const wildcardAttribute = attribute.replace(/(.\d+.)/g, '.*.')

    // Replaces `._[` with `{blank space}` make the attribute a bit more presentable
    const spacedAttribute = attribute.replace(/[_.[]/g, ' ').replace(/]/g, '')

    return attributeNames[wildcardAttribute] || spacedAttribute
  })

oferrero avatar Mar 12 '21 03:03 oferrero

@oferrero I am curious how your data (and rules) appear for this implementation? I can see what you are requesting, but would like to see your implementation so that I can better advise (and potentially adjust) the internals.

mikeerickson avatar Apr 24 '21 17:04 mikeerickson