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

Make full validation result details available (also per field) #212

Merged
merged 2 commits into from
Feb 18, 2024
Merged
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
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,31 @@ The second is when manually validating the model using the `Validate` or `Valida
=> _fluentValidationValidator?.Validate(options => options.IncludeRuleSets("Names"));
}
```

## Access to full `ValidationFailure`
If you need details about the specifics of a validation result (e.g. its `Severity), you can access the result of the
last validation by calling the `GetFailuresFromLastValidation` method on the `FluentValidationValidator` component.

```razor
<div class="validation-message @GetValidationClass()">
<input type="text" @bind="@_person.Name" />
</div>

@code {
private FluentValidationValidator? _fluentValidationValidator;

private string GetValidationClass()
{
var lastResult = _fluentValidationValidator?.GetFailuresFromLastValidation();
if (lastResult is null || !lastResult.Any())
{
return "valid";
}
if (lastResult.Any(failure => failure.Severity == Severity.Error))
{
return "invalid";
}
return "warning";
}
}
```
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using FluentValidation;
using FluentValidation.Internal;
using FluentValidation.Results;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using static FluentValidation.AssemblyScanner;
Expand Down Expand Up @@ -57,10 +58,21 @@ private static async Task ValidateModel(EditContext editContext,
var validationResults = await asyncValidationTask;

messages.Clear();
fluentValidationValidator.LastValidationResult = new Dictionary<FieldIdentifier, List<ValidationFailure>>();

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

if (fluentValidationValidator.LastValidationResult.TryGetValue(fieldIdentifier, out var failures))
{
failures.Add(validationResult);
}
else
{
fluentValidationValidator.LastValidationResult.Add(fieldIdentifier, new List<ValidationFailure> { validationResult });
}
}

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

public bool Validate(Action<ValidationStrategy<object>>? options = null)
{
Expand Down Expand Up @@ -81,4 +82,23 @@ protected override void OnInitialized()

CurrentEditContext.AddFluentValidation(ServiceProvider, DisableAssemblyScanning, Validator, this);
}

/// <summary>
/// Gets the full details of the last validation result, optionally by field.
/// </summary>
/// <param name="fieldIdentifier">If set, only returns the validation failures pertaining to the given field.</param>
/// <returns>Validation failures.</returns>
public ValidationFailure[] GetFailuresFromLastValidation(FieldIdentifier? fieldIdentifier = null)
{
if (LastValidationResult is null)
return Array.Empty<ValidationFailure>();

if (fieldIdentifier is null)
return LastValidationResult.Values.SelectMany(f => f).ToArray();

if (!LastValidationResult.TryGetValue(fieldIdentifier.Value, out var failures))
return Array.Empty<ValidationFailure>();

return failures.ToArray();
}
}
Loading