FluentValidation: Client-side validation not working

I have a validator that is working correctly but I haven’t yet been able to get the respective client-side validation to work.

    FluentValidationModelValidatorProvider.Configure(provider => 
            {
                provider.ValidatorFactory = new BrandValidationFactory();
                provider.Add(
                            typeof(RequiredIfStatusIsEmployedOrSelfEmployedValidator),
                            (metadata, context, rule, validator) => new RequiredIfStatusIsEmployedOrSelfEmployedClientValidator(metadata, context, rule, validator));
            });

RequiredIfStatusIsEmployedOrSelfEmployedValidator inherits PropertyValidator and overrides the protected method:

protected override bool IsValid(PropertyValidatorContext context)
        {
            if (!EmployedStatuses.Contains(applicationFormContext.Application.MainApplicant.EmploymentStatusId.ToUnderlyingType().ToString(CultureInfo.InvariantCulture)))
            {
                return true;
            }

            return context.PropertyValue != null && !IsInvalidString(context.PropertyValue);
        }

RequiredIfStatusIsEmployedOrSelfEmployedClientValidator inherits FluentValidationPropertyValidator and overrides the public method:

public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            yield return new ModelClientValidationMinLengthRule("testError1", 100);
        }

Finally, the configure method:

FluentValidationModelValidatorProvider.Configure(provider => 
            {
                provider.ValidatorFactory = new BrandValidationFactory();
                provider.Add(
                            typeof(RequiredIfStatusIsEmployedOrSelfEmployedValidator),
                            (metadata, context, rule, validator) => new RequiredIfStatusIsEmployedOrSelfEmployedClientValidator(metadata, context, rule, validator));
            });

The client validator never gets called and, therefore, the data- attributes never get rendered on the HTML.

What am I missing?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

Yes you must always provide a string source used to generate the message. The recommended approach is to define the “default” message in the custom property validator’s constructor (this is how FV’s default validators all work), which you can then override using WithMessage if needed.