Below, I have a working example that I would like to modify.
If I run the example below, wipe out the data in the sole input field, and tab out, the validation runs correctly. Alternatively, if I enter more than 10 characters of data and tab out of the input field, the expected error message is displayed.
Home.razor:
@page "/"
@rendermode InteractiveServer
@using Blazored.FluentValidation
@using FluentValidation
<PageTitle>Home</PageTitle>
<EditForm Model="@FormModel">
<FluentValidationValidator Validator=@Validator />
<ValidationSummary />
<InputText @bind-Value="@FormModel.Name" />
</EditForm>
@code {
private SampleData FormModel { get; set; } = new () { Name = "foo" };
private SampleDataValidator Validator = new();
public class SampleDataValidator : AbstractValidator<SampleData>
{
public SampleDataValidator()
{
RuleFor(item => item.Name).NotEmpty().MaximumLength(10);
}
}
public class SampleData
{
public int ID { get; set; }
public string Name { get; set; }
}
}
Now, I'd like to modify the above to use a custom component (TextBoxWrapper) instead of <InputText>. So, I modify one line, replacing the following:
<InputText @bind-Value="@FormModel.Name" />
with the following:
<TextBoxWrapper @bind-Value="@FormModel.Name" />
TextBoxWrapper.razor:
<InputText Value="@Value"
ValueChanged="TextBoxValueChanged"
ValueExpression="() => Value" />
@code {
[Parameter]
public string Value { get; set; } = string.Empty;
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
private async Task TextBoxValueChanged(string newValue)
{
Value = newValue;
if (ValueChanged.HasDelegate)
{
await ValueChanged.InvokeAsync(newValue);
}
}
}
The above does not work and produces the following exception when data is modified at runtime:
System.InvalidOperationException: Cannot validate instances of type 'TextBoxWrapper'. This validator can only validate instances of type 'SampleData'.
Is there a way I can use a custom component similar to TextBoxWrapper and still get validation to work?
Below, I have a working example that I would like to modify.
If I run the example below, wipe out the data in the sole input field, and tab out, the validation runs correctly. Alternatively, if I enter more than 10 characters of data and tab out of the input field, the expected error message is displayed.
Home.razor:
Now, I'd like to modify the above to use a custom component (TextBoxWrapper) instead of
<InputText>
. So, I modify one line, replacing the following:<InputText @bind-Value="@FormModel.Name" />
with the following:
<TextBoxWrapper @bind-Value="@FormModel.Name" />
TextBoxWrapper.razor:
The above does not work and produces the following exception when data is modified at runtime:
System.InvalidOperationException: Cannot validate instances of type 'TextBoxWrapper'. This validator can only validate instances of type 'SampleData'.
Is there a way I can use a custom component similar to TextBoxWrapper and still get validation to work?
Thanks, Michael