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

New Post: Validate 2 of 5 text boxes are not null

$
0
0
You probably already have a solution for this. If not, something like this should work:
[Validator(typeof (InvoicePrintValidator))]
    public class InvoicePrintViewModel
    {
        [DisplayName("Account Number")]
        public string AccountNumber { get; set; }

        [DisplayName("Invoice Number")]
        public string InvoiceNumber { get; set; }

        [DisplayName("Purchase Order Number")]
        public string PurchaseOrderNumber { get; set; }

        [DisplayName("Unit Number")]
        public string UnitNumber { get; set; }

        [DisplayName("Zip Code")]
        public string ZipCode { get; set; }
    }

    public class InvoicePrintValidator : AbstractValidator<InvoicePrintViewModel>
    {
        public InvoicePrintValidator()
        {
            RuleFor(model => model.AccountNumber)
                .NotEmpty()
                .When(AtLeastTwoValuesAreNotNull);

            RuleFor(model => model.InvoiceNumber)
                .NotEmpty()
                .When(AtLeastTwoValuesAreNotNull);

            RuleFor(model => model.UnitNumber)
                .NotEmpty()
                .When(AtLeastTwoValuesAreNotNull);

            RuleFor(model => model.PurchaseOrderNumber)
                .NotEmpty()
                .When(AtLeastTwoValuesAreNotNull);

            RuleFor(model => model.ZipCode)
                .NotEmpty()
                .When(AtLeastTwoValuesAreNotNull);
        }

        private bool AtLeastTwoValuesAreNotNull(InvoicePrintViewModel model)
        {
            return new[]
            {
                model.AccountNumber,
                model.InvoiceNumber,
                model.PurchaseOrderNumber,
                model.UnitNumber,
                model.ZipCode
            }.Count(x => !string.IsNullOrWhiteSpace(x)) >= 2;
        }
    }

Viewing all articles
Browse latest Browse all 1917

Trending Articles



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