Custom Validator with async method

I'm trying to validate the value entered into a textbox by checking to see if its value is in a database. When using the CustomValidator you have the Validator func but my method is async. Is it possible to use an async method with the CustomValidator?

Hi @dcombs,

Tthe Blazor validation framework doesn't support that. Still you can test with

MyMethod().GetResult()
1 Like

I tried using the Result property and the program will deadlock. The only way to get this to work was to use a synchronous method. Thank you for looking at this. :slight_smile:

I´ve got a workaround (kind of). If you are interested let me know.

@horaciodiez, I'm all ears!

Hi @dcombs !
I tell you what i did. .

I set a ref to the RadzenTemplateForm like this:

<RadzenTemplateForm TItem=ActividadRubro Data=@ActividadRubroModelo @ref="templateForm" > 

Of course i declare the templateForm property in my .cs

public RadzenTemplateForm<ActividadRubro> templateForm { get; set; }

I ensure the "Save" button in NOT a Submit button type (in my case "Save" == "Aceptar"

<RadzenButton Text="Aceptar" Click="@Aceptar_Clicked" ButtonStyle="ButtonStyle.Primary" />

I set a RadzenCustomValidator below the property I need to validate using "async await" like this

<RadzenCustomValidator Component="Descripcion" Validator="@(() => string.IsNullOrWhiteSpace(errorMsgs["Descripcion"]) )" Text=@errorMsgs["Descripcion"] />

The idea is: if the error message for the property is empty then the field has a valid value. In my case, i used a dictionary<string, string> where the key is the property name and the value is the error message

Finally at the "Save" event (in my case Aceptar_Clicked) I do something like this

 public async Task Aceptar_Clicked()
 {
        if (!await Valido())  return;
        ....

And then in the "Valido" method

... 
ObjCollection<ActividadRubro> oAr = await dataCall.ActividadRubro_GetAll(ActividadRubroModelo.Descripcion);
if (oAr?.lDynamic?.Count > 0) 
{
       errorMsgs["Descripcion"] = "Descripción ya Existe";
}

//This line executes all the validators 
templateForm.EditContext.Validate();

return templateForm.IsValid;

So, the key is to use the EditContext.Validate() method inside the Save event
Hope this helps.

2 Likes

this is excellent. thank you for walking me through this. i can't wait to try this out!

Ok! Let me know how it goes.

I tried what you recommended. It works great, but method EditContext.Validate() calls all the validators on the page? Is there a way how to call just one specific validator?

@Terezia_Sochova you can call the validator on just one component if you call the following method and pass the string variable componentName with the name of the component, used in the .razor file:

templateForm.EditContext.NotifyFieldChanged(templateForm.FindComponent(componentName).FieldIdentifier);