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

New Post: Check a property is unique in list

$
0
0
I am trying to ensure that a list has unique SSN's. I am getting the "Property name could not be automatically determined for expression element => element. Please specify either a custom property name by calling 'WithName'" error. Would we know what I am doing wrong here?
    using FluentValidation;
        using FluentValidation.Validators;

        public class PersonsValidator : AbstractValidator<Persons>    
        {
            public PersonsValidator()
            {
                this.RuleFor(element=>element).SetValidator(new SSNNumbersInHouseHoldShouldBeUnique<Persons>()).WithMessage("SSN's in household should be unique");
            }
        }

        public class SSNNumbersInHouseHoldShouldBeUnique<T> : PropertyValidator
        {
            public SSNNumbersInHouseHoldShouldBeUnique(): base("SSN's in household should be unique")
            {
            }

            protected override bool IsValid(PropertyValidatorContext context)
            {
                var persons = context.Instance as Persons;
                try
                {
                    if (persons == null)
                    {
                        return false;
                    }

                    var persons = persons.Where(
                        element => element.SSN.Trim().Length > 0);
                    var allSSNs = persons.Select(element => element.SSN.Trim());
                    if (allSSNs.Count() > allSSNs.Distinct().Count())
                    {
                        return false;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
public class Persons : List<Person>
{}

public class Person
{
public string SSN{ get; set; }
}

Viewing all articles
Browse latest Browse all 1917

Trending Articles



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