Validation in ASP.NET MVC 2

I have some issues with validation using data annotations in ASP.NET MVC 2. For example, I have an Address class:

public class Address
{
    public long Id { get; set; }

    [Required]
    public string City { get; set; }

    [Required]
    public string PostalCode { get; set; }

    [Required]
    public string Street { get; set; }
}

And order class:

public class Order
{
    public long Id { get; set; }

    public Address FirstAddress { get; set; }

    public Address SecondAddress { get; set; }

    public bool RequireSecondAddress { get; set; }
}

I want to check Order.FirstAddress all the time, but Order.SecondAddress should only be checked if Order.RequireSecondAddress is set to true.

Any ideas? :)

Chris

+3
source share
2 answers

This is almost impossible with data annotations, or it will require writing ugly code based on reflection, etc. (I think you understand).

FluentValidation. ASP.NET MVC. :

public class AddressValidator : AbstractValidator<Address>
{
    public AddressValidator()
    {
        RuleFor(x => x.City)
            .NotEmpty();
        RuleFor(x => x.PostalCode)
            .NotEmpty();
        RuleFor(x => x.Street)
            .NotEmpty();
    }
}

public class OrderValidator : AbstractValidator<Order>
{
    public OrderValidator()
    {
        RuleFor(x => x.FirstAddress)
            .SetValidator(new AddressValidator());
        RuleFor(x => x.SecondAddress)
            .SetValidator(new AddressValidator())
            .When(x => x.RequireSecondAddress);
    }
}

, , .

+3
+1

Source: https://habr.com/ru/post/1767336/


All Articles