Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Greater than or equals comparison against an enum with Fluent Validation?

$
0
0

Hi

The error you're seeing ("The validator 'FirstValidator' cannot validate members of type 'MyEnum' - the types are not compatible") is because by using SetValidator you're trying to validate the anEnum *property* with FirstValidator (which can only validate instances of MyObject) - this isn't the correct approach. If you want to trigger rules based on the enum property, you need to use FluentValidation's support for conditions.

If you've only got a single rule, then you can do this:

public class MyObjectValidator : AbstractValidator<MyObject> {

	public MyObjectValidator() {
		RuleFor(x => x.someDecimal).Equal(1).When(x => x.anEnum == MyObject.MyEnum.First);
	}

}

...alternatively, if you want to apply the same condition to multiple rules, you can use a single condition using the top-level When method:

public class MyObjectValidator : AbstractValidator<MyObject> {

	public MyObjectValidator() {
		
		When(x => x.anEnum == MyObject.MyEnum.First, () => {
			RuleFor(x => x.someDecimal).Equal(1);
			//other rules can go here

		});
	}

}

I'll cross-post this to StackOverflow.

Jeremy


Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>