0

Is there a way to return multiple messages on one rule?

public class EmployeeValidator : AbstractValidator<Employee>
{
    public EmployeeValidator ()
    {
      RuleFor(p => p.StartDate).Custom(ValidateStartDate);
    }
    
    private void ValidateStartDate(DateTime? startDate, ValidationContext<Employee>   context)
    {
    var gap = context.InstanceToValidate;
    
    if(startDate != null && startDate > DateTime.Noew.Date)
    {
         context.AddFailure(new ValidationFailure(nameof(gap.StartDate), "Start Date mustn't be in future."); // Message 1
    }

    if(condition)
    {
         context.AddFailure(new ValidationFailure(nameof(gap.StartDate), "Employee must be registered on this date."); // Message 2
    }
}
}

In the Blazor app:

   <MudDatePicker Label="Start Date" @bind-Date="employee.StartDate" Mask="@(new DateMask("MM/dd/yyyy"))"
                  DateFormat="MM/dd/yyyy"  ShowToolbar="false"
                  Variant="Variant.Outlined" Margin="Margin.Dense" Editable="true" For="() => employee.StartDate"></MudDatePicker>

This is always displaying message 2. Is it possible to display both the messages at once?

9
  • AFAIK from MudInputControl, it will only display 1 message Commented Feb 25 at 3:23
  • are you using the FluentValidation or Blazored.FluentValidation package? Commented Feb 25 at 10:44
  • Blazored.FluentValidation Commented Feb 25 at 13:30
  • could you try this: var errorlist = new List<string>(); if (startDate != null && startDate > DateTime.Now.Date) { errorlist.Add("Start Date mustn't be in future."); } if (condition) { errorlist.Add("Employee must be registered on this date."); } if (errorlist.Count > 0) { var errormessage = string.Join("<br/>", errorlist); context.AddFailure(new ValidationFailure(nameof(gap.StartDate), errormessage)); } Commented Feb 26 at 10:56
  • I already tried but it's displaying <br/> as is. Commented Feb 26 at 20:12

1 Answer 1

0

You could try this below code:

let's say I have two condition first will check the null date and second will check the grater than today's day

using FluentValidation;

namespace BlazorApp2
{
    public class EmployeeValidator : AbstractValidator<Employee>

    {
        public EmployeeValidator()
        {
            RuleFor(p => p.StartDate).Custom(ValidateStartDate);
        }
        private void ValidateStartDate(DateTime? startDate, ValidationContext<Employee> context)
        {
            var employee = context.InstanceToValidate;

            // First Validation: Start Date mustn't be in future.
            if (startDate != null)
            {
                context.AddFailure(nameof(employee.StartDate), "Start Date mustn't be in future.");
                
            }

            // Second Validation: Employee must be registered on this date.
            if (startDate > DateTime.Now.Date)
            {
                context.AddFailure(nameof(employee.StartDate), "Employee must be registered on this date.");
            }
        }

    }
}

enter image description here

OR

One condition will check future date selection and second will show past selection:

// First Validation: Start Date mustn't be in future.
 if (startDate != null && startDate > DateTime.Now.Date)
 {
     context.AddFailure(nameof(employee.StartDate), "Start Date mustn't be in future.");
 }
 // Second Validation: Employee must be registered on this date.
 if (startDate != null && startDate < DateTime.Now.AddYears(-1).Date)
 {
     context.AddFailure(nameof(employee.StartDate), "Employee must be registered on this date.");
 }

razor page:

@page "/"
@using FluentValidation
@using MudBlazor
@inject IValidator<Employee> EmployeeValidator

<EditForm Model="@employee" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <MudForm @ref="form" Model="@employee">
        <MudTextField Label="Name" @bind-Value="employee.Name" />
        <MudDatePicker Label="Start Date" @bind-Date="employee.StartDate" Mask="@(new DateMask("MM/dd/yyyy"))"
                       DateFormat="MM/dd/yyyy" ShowToolbar="false"
                       Variant="Variant.Outlined" Margin="Margin.Dense" Editable="true">
        </MudDatePicker>
        <MudButton OnClick="ValidateForm" Variant="Variant.Filled" Color="Color.Primary">Submit</MudButton>
    </MudForm>
</EditForm>

@code {
    private Employee employee = new Employee();
    private MudForm form;

    private async Task ValidateForm()
    {
        var result = await EmployeeValidator.ValidateAsync(employee);
        if (result.IsValid)
        {
            Console.WriteLine("Form Submitted Successfully!");
        }
        else
        {
            // Log all validation errors
            foreach (var failure in result.Errors)
            {
                Console.WriteLine(failure.ErrorMessage);
            }
        }
    }

    private void HandleValidSubmit()
    {
        // Handle submission logic after the form is valid
        Console.WriteLine("Form submitted successfully.");
    }
}

Let me know if you have any concern regarding the provided information or my understanding is different

enter image description here

enter image description here

update:

EmployeeValidator.cs:

using FluentValidation;
using FluentValidation.Results;

namespace BlazorApp2
{
    public class EmployeeValidator : AbstractValidator<Employee>

    {
        public EmployeeValidator()
        {
            RuleFor(p => p.StartDate).Custom(ValidateStartDate);
        }
        private void ValidateStartDate(DateTime? startDate, ValidationContext<Employee> context)
        {
            var employee = context.InstanceToValidate;
            var failures = new List<ValidationFailure>();
            // Condition 1: Start Date is required
            if (startDate == null)
            {
                failures.Add(new ValidationFailure(nameof(employee.StartDate), "Start Date is required."));
            }
            else
            {
                var publicHolidays = new List<DateTime>
                {
                    new DateTime(DateTime.Now.Year, 12, 25), // Christmas
                    new DateTime(DateTime.Now.Year, 1, 1)   // New Year
                };
                // Condition 2: Start Date must not be in the future
                if (startDate > DateTime.Now.Date)
                {
                    failures.Add(new ValidationFailure(nameof(employee.StartDate), "Start Date mustn't be in future."));
                }
                // Condition 3: Employee must be registered at least 1 year ago
                if (startDate < DateTime.Now.AddYears(-1).Date)
                {
                    failures.Add(new ValidationFailure(nameof(employee.StartDate), "Employee must be registered on this date."));
                }
                // Condition 4: Start Date should not be on weekends
                if (startDate.Value.DayOfWeek == DayOfWeek.Saturday || startDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    failures.Add(new ValidationFailure(nameof(employee.StartDate), "Start Date cannot be on a weekend."));
                }
                // Condition 5: Start Date should not be on a public holiday
                if (publicHolidays.Contains(startDate.Value))
                {
                    failures.Add(new ValidationFailure(nameof(employee.StartDate), "Start Date cannot be on a public holiday."));
                }
            }
            // Add all failures at once so they appear together
            foreach (var failure in failures)
            {
                context.AddFailure(failure);
            }
        }

    }
}

Home.razor:

@page "/"
@using FluentValidation
@using MudBlazor
@inject IValidator<Employee> EmployeeValidator
<EditForm Model="@employee" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <MudForm @ref="form" Model="@employee">
        <ValidationSummary /> <!-- This will display all validation messages -->

        <MudTextField Label="Name" @bind-Value="employee.Name" />
        <MudDatePicker Label="Start Date" @bind-Date="employee.StartDate" Mask="@(new DateMask("MM/dd/yyyy"))"
                       DateFormat="MM/dd/yyyy" ShowToolbar="false"
                       Variant="Variant.Outlined" Margin="Margin.Dense" Editable="true">
        </MudDatePicker>

        <!-- Display all validation messages dynamically below the field -->
        <ul>
            @foreach (var error in validationMessages)
            {
                <li style="color: red;">@error</li>
            }
        </ul>

        <MudButton OnClick="ValidateForm" Variant="Variant.Filled" Color="Color.Primary">Submit</MudButton>
    </MudForm>
</EditForm>
@code {
    private Employee employee = new Employee();
    private MudForm form;
    private List<string> validationMessages = new List<string>();
    private async Task ValidateForm()
    {
        validationMessages.Clear();  // Clear previous messages
        var result = await EmployeeValidator.ValidateAsync(employee);
        if (result.IsValid)
        {
            Console.WriteLine("Form Submitted Successfully!");
        }
        else
        {
            foreach (var failure in result.Errors)
            {
                validationMessages.Add(failure.ErrorMessage);  // Store all errors
            }
        }
    }
    private void HandleValidSubmit()
    {
        Console.WriteLine("Form submitted successfully.");
    }
}

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.