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.

Stop on first failure

See original GitHub issue

System Details

  • FluentValidation version: 8.4.0

Issue Description

Is it possible to stop validation on first failure? I could not find the answer in github and also stack overflow. I hope that someone can help me.

Here is the current code I find in github

public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidationRule> {
   internal TrackingCollection<IValidationRule> Rules { get; } = new TrackingCollection<IValidationRule>();
   public async virtual Task<ValidationResult> ValidateAsync(ValidationContext<T> context, CancellationToken cancellation = new CancellationToken()) {
	context.Guard("Cannot pass null to Validate", nameof(context));
	context.RootContextData["__FV_IsAsyncExecution"] = true;
	var result = new ValidationResult();
	bool shouldContinue = PreValidate(context, result);
	if (!shouldContinue) {
		return result;
	}
	EnsureInstanceNotNull(context.InstanceToValidate);
	foreach (var rule in Rules) {
		cancellation.ThrowIfCancellationRequested();
		var failures = await rule.ValidateAsync(context, cancellation);
		foreach (var failure in failures.Where(f => f != null)) {
			result.Errors.Add(failure);
		}
	}
	SetExecutedRulesets(result, context);
	return result;
}

In order to tackle my problem, I need to override our current ValidateAsync like this

public override async Task<ValidationResult> ValidateAsync(ValidationContext<T> context, CancellationToken cancellation = default(CancellationToken))
        {
            context.RootContextData["__FV_IsAsyncExecution"] = true;
            var result = new ValidationResult();
            var rules = (IEnumerable<IValidationRule>)this.GetType().GetProperty("Rules", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic).GetValue(this);
            foreach (var rule in rules)
            {
                cancellation.ThrowIfCancellationRequested();
                var failures = await rule.ValidateAsync(context, cancellation);
                foreach (var failure in failures.Where(f => f != null))
                {
                    result.Errors.Add(failure);
                }
                // stop on first error
                if (result.Errors.Any())
                {
                    return result;
                }
            }
            return result;
        }

but it is too ugly imo.

Thanks,

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
lust4lifecommented, Sep 18, 2019

@minhtd1981 maybe you can set some context when there is an error occur in OnFailure, then check it to decide whether execution needs to continue in ‘Selector.CanExecute’ like what RuleSets do. But this should be only used in general cases, when in advanced case , DependentRules should be used.

but if @JeremySkinner can add some options for this case like what you do (skip other rules when first rule has some errors), that would be nice for case when need fast failed check.

0reactions
minhtd1981commented, Sep 9, 2019

Hi @JeremySkinner,

If there is no other way around, I will stick with DependentRules.

FYI. base.Validate(context) will validate all other property rules and that causes database hits.

I was not aware that Validator implements IEnumerable<IValidationRule> that is really cool.

Thanks a lot,

Read more comments on GitHub >

github_iconTop Results From Across the Web

long running py.test stop at first failure
pytest -x # stop after first failure pytest --maxfail=2 # stop after ... the execution of the tests instanly on first error or...
Read more >
Stop testing a file on first fail · Issue #9515 · pytest-dev ...
-x is useful in this case. There is also --max-fail=n to fail on n number of failures. pytest also has other modes like...
Read more >
Jest — Fail Early (And Stop Testing If One Test Fails)
Stopping the test run after the first failed test saves you time, especially during development. Jest comes with a built-in feature to fail...
Read more >
PyTest: stop on first failure - Code Maven
PyTest: stop on first failure. pytest -x pytest --maxfail 42. Index (i) · Table of Contents (t) · Indexed keywords (k) · Chapter...
Read more >
Stop RSpec on the first failure with the -​-fail-fast ...
When running a project's RSpec test suite locally, have RSpec automatically stop on the first test failure with the --fail-fast command-line ...
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