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

Option to provide RootContextData #156

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
6 changes: 5 additions & 1 deletion samples/BlazorServer/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<hr class="mb-5" />

<EditForm Model="@_person" OnValidSubmit="@SubmitValidForm">
<FluentValidationValidator @ref="_fluentValidationValidator" DisableAssemblyScanning="@true" />
<FluentValidationValidator @ref="_fluentValidationValidator" DisableAssemblyScanning="@true" ContextData="_data" />
<ValidationSummary />

<p>
Expand Down Expand Up @@ -72,6 +72,10 @@
@code {
private readonly Person _person = new();
private FluentValidationValidator? _fluentValidationValidator;
private readonly IDictionary<string, object> _data = new Dictionary<string, object>
{
{ "MinAgeLimit", 18 }
};

private void SubmitValidForm()
=> Console.WriteLine("Form Submitted Successfully!");
Expand Down
6 changes: 5 additions & 1 deletion samples/BlazorWebAssembly/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<hr class="mb-5" />

<EditForm Model="@_person" OnSubmit="@SubmitFormAsync">
<FluentValidationValidator @ref="_fluentValidationValidator" Options="@(options => options.IncludeAllRuleSets())" />
<FluentValidationValidator @ref="_fluentValidationValidator" Options="@(options => options.IncludeAllRuleSets())" ContextData="_data" />
<ValidationSummary />

<p>
Expand Down Expand Up @@ -72,6 +72,10 @@
@code {
private readonly Person _person = new();
private FluentValidationValidator? _fluentValidationValidator;
private readonly IDictionary<string, object> _data = new Dictionary<string, object>
{
{ "MinAgeLimit", 18 }
};

private async Task SubmitFormAsync()
{
Expand Down
7 changes: 7 additions & 0 deletions samples/Shared/SharedModels/Person.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ public PersonValidator()

RuleFor(p => p.Age)
.NotNull().WithMessage("You must enter your age")
.Custom((age, context) =>
{
if (context.RootContextData.TryGetValue("MinAgeLimit", out var ageValue) && ageValue is int minAge && age < minAge)
{
context.AddFailure($"Age must be greater than {minAge}");
}
})
.GreaterThanOrEqualTo(0).WithMessage("Age must be greater than 0")
.LessThan(150).WithMessage("Age cannot be greater than 150");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static void AddFluentValidation(this EditContext editContext, IServicePro
async (sender, _) => await ValidateModel((EditContext)sender!, messages, serviceProvider, disableAssemblyScanning, fluentValidationValidator, validator);

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

private static async Task ValidateModel(EditContext editContext,
Expand Down Expand Up @@ -52,6 +52,8 @@ private static async Task ValidateModel(EditContext editContext,
context = new ValidationContext<object>(editContext.Model);
}

FillRootContextData(context, fluentValidationValidator.ContextData);

var asyncValidationTask = validator.ValidateAsync(context);
editContext.Properties[PendingAsyncValidation] = asyncValidationTask;
var validationResults = await asyncValidationTask;
Expand All @@ -72,11 +74,14 @@ private static async Task ValidateField(EditContext editContext,
FieldIdentifier fieldIdentifier,
IServiceProvider serviceProvider,
bool disableAssemblyScanning,
FluentValidationValidator fluentValidationValidator,
IValidator? validator = null)
{
var properties = new[] { fieldIdentifier.FieldName };
var context = new ValidationContext<object>(fieldIdentifier.Model, new PropertyChain(), new MemberNameValidatorSelector(properties));


FillRootContextData(context, fluentValidationValidator.ContextData);

validator ??= GetValidatorForModel(serviceProvider, fieldIdentifier.Model, disableAssemblyScanning);

if (validator is not null)
Expand Down Expand Up @@ -219,4 +224,15 @@ private static FieldIdentifier ToFieldIdentifier(in EditContext editContext, in
}
}
}

private static void FillRootContextData(ValidationContext<object> context, IDictionary<string, object>? data)
{
if (data is not null)
{
foreach (var item in data)
{
context.RootContextData[item.Key] = item.Value;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public class FluentValidationValidator : ComponentBase
[Parameter] public IValidator? Validator { get; set; }
[Parameter] public bool DisableAssemblyScanning { get; set; }
[Parameter] public Action<ValidationStrategy<object>>? Options { get; set; }
[Parameter] public IDictionary<string, object>? ContextData { get; set; }
internal Action<ValidationStrategy<object>>? ValidateOptions { get; set; }

public bool Validate(Action<ValidationStrategy<object>>? options = null)
Expand Down