public class CustomValidator : ComponentBase
{
private ValidationMessageStore messageStore;
[CascadingParameter] public EditContext CurrentEditContext { get; set; }
protected override void OnInitialized()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException(
"To use validator component your razor page should have the edit component");
}
messageStore = new ValidationMessageStore(CurrentEditContext);
// Clear Error Message On Raise Of OnValidationRequested Form Event
CurrentEditContext.OnValidationRequested += (s, e) => messageStore.Clear();
// Clear Error Message On Input Field Change Event
CurrentEditContext.OnFieldChanged += (s, e) => messageStore.Clear(e.FieldIdentifier);
}
public void DisplayErrors(Dictionary<string, List<string>> errors)
{
foreach (var error in errors)
{
messageStore.Add(CurrentEditContext.Field(error.Key), error.Value);
}
CurrentEditContext.NotifyValidationStateChanged();
}
public void DisplayErrors(string fieldName, List<string> errors)
{
foreach (var error in errors)
{
messageStore.Add(CurrentEditContext.Field(fieldName), error);
}
CurrentEditContext.NotifyValidationStateChanged();
}
}
App.razor
<EditForm Model="@_model" OnValidSubmit="ValidSubmit">
<DataAnnotationsValidator/>
<ValidationSummary/>
<CustomValidator @ref="_customValidator"></CustomValidator>
...
@code {
private CustomValidator _customValidator;
...
private async Task ValidSubmit(EditContext obj)
{
if (await CheckValidations())
{
if (OnSubmit.HasDelegate)
{
Customer.Customerr = _model.Customer.TrimText();
Customer.ProvinceUUID = _model.ProvinceUUID;
Customer.CityUUID = _model.CityUUID;
await OnSubmit.InvokeAsync(new NewCustomerInfoEventArgs()
{
Customer = Customer,
});
}
}
}
private async Task<bool> CheckValidations()
{
int errors = 0;
ApplicationDbContext context = await DbFactory.CreateDbContextAsync();
var customer = _model.Customer.TrimText();
var isExist = await context.DcCustomers.AnyAsync(x => x.Customerr == customer);
await context.DisposeAsync();
if (isExist)
{
_customValidator.DisplayErrors(nameof(_model.Customer), new List<string> { "نام مشتری تکراری است" });
errors += 1;
}
if (errors == 0)
{
return true;
}
return false;
}
References
https://www.learmoreseekmore.com/2021/01/blazor-server-forms-validator-component.html