Skip to content

[REQUEST] Add a way to provide a custom error message to validator #69

@omer-g

Description

@omer-g

Is your feature request related to a problem? Please describe.
Currently, it seems that there is no way to programmatically iterate over validation errors and print a custom error message for each. In the documentation, an {#if} statement is used to print errors one by one.

  {#if $myForm.hasError('name.required')}
    <div>Name is required</div>
  {/if}

It's possible for users to maintain an additional object that maps a validator's name to a custom error message, but that is rather cumbersome and "boilerplatey".

Describe the solution you'd like
Add an optional errorMessage property to the object returned by the (inner) validation function in Validator. The type of the property could be () => string | string. This would allow one to programmatically generate custom error messages based on current input value at the time of validation (or static messages as well).

Describe alternatives you've considered
Provide a separate object that maps each validator name to an (optional) error message (which is of type () => string | string). This has the benefit of not requiring a change in the signature of Validator. An additional method could be included that iterates over current error messages. A drawback is that it relies on the user entering unique names to validators (not sure if that might already be the case?).

Additional context
There is currently a pull request (#50) by @eden-omb that relates to a similar issue. From what I understand, they suggest to use the name property to pass informative errors. This would be helpful but has three main issues:

  1. Developers may wish to use name of Validator as a key in their own objects that need a string key. Validation error messages are not always unique, and it's probably preferable not to use error messages as keys.
  2. The error message provided must be static and cannot be generated based on current input value. For example: between(5, 10, "Must be between 5 and 10") cannot have a message such as: 4 is not between 5 and 10.
  3. The property is called name and not, for example, errorMessage.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions