Search code examples
asp.net-mvcvalidationfluentvalidation

FluentValidation centralize a regex validator in validator extension


I have a validation rule that is common for many properties that I'd like to centralize to DRY, but while NotEmpty() rules and the like work fine, Matches(...) and other string-only validator rules don't compile.

No problem:

    public static IRuleBuilderOptions<T, TProperty> MustNotContainHtml<T, TProperty>(this IRuleBuilderOptions<T, TProperty> ruleBuilder)       
    {
        return ruleBuilder.NotEmpty().WithMessage("Some message.");
    }

Understandably won't compile because uses Matches(...) which is string-only:

    public static IRuleBuilderOptions<T, TProperty> MustNotContainHtml<T, TProperty>(this IRuleBuilderOptions<T, TProperty> ruleBuilder)
    {
        return ruleBuilder.Matches("<[a-z!/?]|&#").WithMessage("'{PropertyName}' contains special HTML characters which is not allowed.");
    }

What rule builder signature is there available for string-only options?


Solution

  • The solution is to reuse the actual RegularExpressionValidator:

        public static IRuleBuilderOptions<T, string> MustNotContainHtml<T>(this IRuleBuilder<T, string> ruleBuilder)
        {
            return ruleBuilder.SetValidator(new RegularExpressionValidator("<[a-z!/?]|&#")).WithMessage("Some custom message.");
        }