Inquirer icon indicating copy to clipboard operation
Inquirer copied to clipboard

Option for the consumer to override the error message?

Open mii9000 opened this issue 5 years ago • 5 comments

I suggest there should be an option for the user of the library to override the error messages of validators. @afucher What do you think? I can work on it.

mii9000 avatar Oct 14 '20 08:10 mii9000

Hey @Ibrahim-Islam , I think that this make sense. Do you have any proposal about how to do that? I was thinking that this is a behaviour of the validator implementation, but would like to understand if you have any idea.

afucher avatar Oct 14 '20 14:10 afucher

@afucher I think a simple optional argument to override the error message when initializing the validator is one option.

mii9000 avatar Oct 14 '20 15:10 mii9000

@afucher How does this API look like?

    public abstract class BaseValidator : IValidator
    {
        protected readonly string Pattern;
        protected string ErrorMessage;

        protected BaseValidator(string pattern, string errorMessage)
        {
            Pattern = pattern;
            ErrorMessage = errorMessage;
        }

        public virtual string GetErrorMessage() => ErrorMessage;

        public abstract bool Validate(string value);
    }

    public class RegexValidator : BaseValidator
    {
        public RegexValidator(string pattern)
            : base(pattern, $"Answer should match pattern {pattern}")
        { }

        public override bool Validate(string value) => Regex.IsMatch(value, Pattern);

        public RegexValidator WithErrorMessage(string message)
        {
            ErrorMessage = message;
            return this;
        }
    }

mii9000 avatar Oct 15 '20 11:10 mii9000

Hey @Ibrahim-Islam , why do we need this abstract class with Pattern ? Others validators doesn't need this.

afucher avatar Oct 16 '20 13:10 afucher

Hey @Ibrahim-Islam , what do you think about an approach more Fluent?

Like:

var validator = new RegexValidator("some pattern").WithErrorMessage("My custom error message");

afucher avatar Oct 21 '20 01:10 afucher