andrebaltieri / FluentValidator

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

Criar novo método AddNotifications #6

Closed pauloanalista closed 6 years ago

pauloanalista commented 7 years ago

Criar um novo método para adicionar notificações das classes notificáveis mais simples.

AddNotifications(cpf, cnpj, dinheiro);

Basta criar um metodo com params

public void AddNotifications(params Notifiable[] objects) { objects.ToList().ForEach(x => _notifications.AddRange(x.Notifications)); }

andrebaltieri commented 6 years ago

Hi Paulo, can you provide a case you need this?

angelobelchior commented 6 years ago

I think the best way to do that is to create an Extension Method to Validate Contract class:

namespace FluentValidator.Validation
{
    public static class MyValidators
    {
        public static ValidationContract IsCPF(this ValidationContract self,
                                               string value,
                                               string property,
                                               string message)
        {
            /*Magic*/
            return self;
        }
    }
}
yanjustino commented 6 years ago

I proposed in PR #13 to improve this. The Concat method creates a notification stack

    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);