question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Client-side validation not working

See original GitHub issue

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?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:18 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
JeremySkinnercommented, Jul 20, 2017

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.

0reactions
fabiomilheirocommented, Jul 20, 2017

Well, I found out. My property validator constructor calls the base constructor with a null string source which is set here:

    protected PropertyValidator(IStringSource errorMessageSource)
    {
      this.originalErrorSource = this.errorSource = errorMessageSource;
    }

The field errorSource is used in the last line of the BuildErrorMessage method:

    private string BuildErrorMessage(PropertyValidatorContext context)
    {
      if (this.customFormatArgs != null && this.customFormatArgs.Count > 0)
      {
        object[] array = this.customFormatArgs.Select<Func<object, object, object>, object>((Func<Func<object, object, object>, object>) (func => func(context.Instance, context.PropertyValue))).ToArray<object>();
        context.MessageFormatter.AppendAdditionalArguments(array);
      }
      object context1 = this.errorSource is IContextAwareStringSource ? (object) context : context.Instance;
      return context.MessageFormatter.BuildMessage(this.errorSource.GetString(context1));
    }

To fix this I could pass a not null error source but I decided to add the message fluently which ends up setting that value too as a StaticStringSource:

    RuleFor(x => x.EmploymentSectorId)
                .SetValidator(new RequiredIfStatusIsEmployedOrSelfEmployedValidator(applicationFormContext))
                .WithName(fields.EmploymentSector.Label)
                .WithMessage("The {PropertyName} is not valid.");

Thanks for your help @JeremySkinner!

Read more comments on GitHub >

github_iconTop Results From Across the Web

MVC 4 client side validation not working
I put a breakpoint in the POST version of my login action method, and it is being hit. The form is posted to...
Read more >
Razor validation not working - Microsoft Q&A
Hi All I have a page that uses Razor validation and for some reason the page no longer validates. I have no idea...
Read more >
Client side validation not firing and Page_Validators ...
What you can check is if the validation is working with a simple ASP controls and verify that the IDs and validation groups...
Read more >
Issues for Clientside Validation
Title Status Priority Category Version Allow specific form ids for clientside validation Needs work Normal Feature request 3.0.x‑d... Firefox error with link validation regex patterns...
Read more >
Form validation not showing required field validator
Solution 2 · Add the settings to your web.config file: <? · Make sure you have the "jqueryval" bundle defined: bundles. · Output...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found