Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented a new method AddValidationResult in FluentValidationVal… #200

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions samples/BlazorServer/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
</EditForm>
<br />
<button @onclick="PartialValidate">Partial Validation</button>
<button @onclick="AddValidationResult">Add Validation Result</button>

@code {
private readonly Person _person = new();
Expand All @@ -78,4 +79,14 @@

private void PartialValidate()
=> Console.WriteLine($"Partial validation result : {_fluentValidationValidator?.Validate(options => options.IncludeRuleSets("Names"))}");

private void AddValidationResult()
{
_fluentValidationValidator!.AddValidationResult(_person, new FluentValidation.Results.ValidationResult
{
Errors = new List<FluentValidation.Results.ValidationFailure> {
new FluentValidation.Results.ValidationFailure { PropertyName = "EmailAddress", ErrorMessage = "This email address is taken already"}
}
});
}
}
11 changes: 11 additions & 0 deletions samples/BlazorWebAssembly/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
</EditForm>
<br />
<button @onclick="PartialValidate">Partial Validation</button>
<button @onclick="AddValidationResult">Add Validation Result</button>

@code {
private readonly Person _person = new();
Expand All @@ -83,4 +84,14 @@

private void PartialValidate()
=> Console.WriteLine($"Partial validation result : {_fluentValidationValidator?.Validate(options => options.IncludeRuleSets("Names"))}");

private void AddValidationResult()
{
_fluentValidationValidator!.AddValidationResult(_person, new FluentValidation.Results.ValidationResult
{
Errors = new List<FluentValidation.Results.ValidationFailure> {
new FluentValidation.Results.ValidationFailure { PropertyName = "EmailAddress", ErrorMessage = "This email address is taken already"}
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,14 @@ public static void AddFluentValidation(this EditContext editContext, IServicePro
{
ArgumentNullException.ThrowIfNull(editContext, nameof(editContext));

var messages = new ValidationMessageStore(editContext);

editContext.OnValidationRequested +=
async (sender, _) => await ValidateModel((EditContext)sender!, messages, serviceProvider, disableAssemblyScanning, fluentValidationValidator, validator);
async (sender, _) => await ValidateModel((EditContext)sender!, serviceProvider, disableAssemblyScanning, fluentValidationValidator, validator);

editContext.OnFieldChanged +=
async (_, eventArgs) => await ValidateField(editContext, messages, eventArgs.FieldIdentifier, serviceProvider, disableAssemblyScanning, validator);
async (_, eventArgs) => await ValidateField(editContext, fluentValidationValidator.Messages, eventArgs.FieldIdentifier, serviceProvider, disableAssemblyScanning, validator);
}

private static async Task ValidateModel(EditContext editContext,
ValidationMessageStore messages,
IServiceProvider serviceProvider,
bool disableAssemblyScanning,
FluentValidationValidator fluentValidationValidator,
Expand Down Expand Up @@ -56,11 +53,11 @@ private static async Task ValidateModel(EditContext editContext,
editContext.Properties[PendingAsyncValidation] = asyncValidationTask;
var validationResults = await asyncValidationTask;

messages.Clear();
fluentValidationValidator.Messages.Clear();
foreach (var validationResult in validationResults.Errors)
{
var fieldIdentifier = ToFieldIdentifier(editContext, validationResult.PropertyName);
messages.Add(fieldIdentifier, validationResult.ErrorMessage);
fluentValidationValidator.Messages.Add(fieldIdentifier, validationResult.ErrorMessage);
}

editContext.NotifyValidationStateChanged();
Expand Down
26 changes: 26 additions & 0 deletions src/Blazored.FluentValidation/FluentValidationsValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public class FluentValidationValidator : ComponentBase
[Parameter] public Action<ValidationStrategy<object>>? Options { get; set; }
internal Action<ValidationStrategy<object>>? ValidateOptions { get; set; }

internal ValidationMessageStore Messages { get; private set; }

public bool Validate(Action<ValidationStrategy<object>>? options = null)
{
if (CurrentEditContext is null)
Expand Down Expand Up @@ -79,6 +81,30 @@ protected override void OnInitialized()
$"inside an {nameof(EditForm)}.");
}

Messages = new ValidationMessageStore(CurrentEditContext);
CurrentEditContext.AddFluentValidation(ServiceProvider, DisableAssemblyScanning, Validator, this);
}

/// <summary>
/// Adds the validation errors contained in a FluentValidation ValidationResult object to the
/// current EditContext's validation messages. This allows for manual validation scenarios where
/// the ValidationResult may not be automatically integrated into Blazor's validation system.
/// Calling this method will update the validation state and the associated UI elements.
/// </summary>
/// <param name="model">The object instance that the validation applies to. This is used to
/// identify the form model within the EditContext.</param>
/// <param name="validationResult">The ValidationResult obtained from FluentValidation that contains
/// the details of any validation errors.</param>
public void AddValidationResult(object model, ValidationResult validationResult)
{
if (CurrentEditContext != null && Messages != null)
{
foreach (ValidationFailure error in validationResult.Errors)
{
var fieldIdentifier = new FieldIdentifier(model, error.PropertyName);
Messages.Add(fieldIdentifier, error.ErrorMessage);
}
CurrentEditContext.NotifyValidationStateChanged();
}
}
}