andrebaltieri / FluentValidator

Fluent Validator is a fluent way to use Notification Pattern with your entities
122 stars 40 forks source link

Improving FluentValidator to provide internal validation. Useful in D… #13

Closed yanjustino closed 6 years ago

yanjustino commented 6 years ago

Improving FluentValidator to provide internal validation. Useful in Domain Contexts. Eg.:

    public class Invoice: Aggregate
    {
        public int Code { get; private set; }
        public DateTime Date { get; private set; }
        public decimal Value { get; private set; }
        public Address Address { get; private set; }

        // Internal Validation
        protected override IEnumerable<Notification> Validations()
        {
            return new ValidationContract()
                .Requires()
                .Concat(Address) // Concat Address Validations
                .IsGreaterThan(Code, 0, "Code", "Code is required")
                .IsGreaterThan(Date, DateTime.MinValue, "Date", "Date is required")
                .Notifications;
        }
    }

    public class Address: Entity
    {
        public string Value{ get; private set; }

        // Internal Validation
        protected override IEnumerable<Notification> Validations()
        {
            return new ValidationContract()
                .Requires()
                .IsNotNullOrEmpty(Name, "Address", "Address is required")
                .Notifications;
        }
    }

    //Test
    Invoice invoice = new Invoice(0, DateTime.Today, 100, new Address("Name"));
    Assert.IsFalse(invoice.IsValid);
    Assert.AreEqual(1, invoice.Notifications.Count);

See NotifiableTest Class for more details.