1

i have written one rule to check whether objects Id within list are not null or empty. But rule is not failing. Is any problem in here with my code ?

NOTE : Id's are of string type.

RuleFor(x => x.MyListOfObjects).Must(x => x.All(x => !string.IsNullOrWhiteSpace(x.Id)))
                        .WithMessage("The Id should not be empty or null.");

Any pointers or suggestions are welcomed.

2
  • 1
    Do you have examples for this rule actually being executed where it is not behaving as expected? For example, do you have unit tests that can reproduce the success and failure behaviors? Have you verified that the validator is being executed in the real code? Commented Jun 11, 2022 at 18:04
  • unit test cases are failing for this scenario. Commented Jun 13, 2022 at 7:24

1 Answer 1

5

I've written the possible example for your code. Looks like everything is ok for your statement if you use fluent validation in the such way (please notice that if one item is "" or null check is still applied):

internal static class Program
        {
            static void Main(string[] args)
            {
                var list = new ListClass();
                var result = list.Validate();
    
                if(!result.IsValid) Console.WriteLine($"Error: {result.Errors.First()}");
            }
    
        }
    
        class ListClass
        {
            public List<Item> List = new List<Item>()
            {
                new Item {Id = "Empty"},
                new Item {Id = null},
                new Item {Id = ""},
            };
    
            private readonly Validator _validator = new Validator();
    
            public ValidationResult Validate() => _validator.Validate(this);
        }
    
        class Item
        {
            public string Id { get; set; }
        }
    
        class Validator : AbstractValidator<ListClass>
        {
            public Validator()
            {
                RuleFor(x => x.List).Must(x => x.All(x => !string.IsNullOrWhiteSpace(x.Id)))
                    .WithMessage("The Id should not be empty or null.");
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.