在blazor razor页面中使用editform时如何重置自定义验证错误 [英] How to reset custom validation errors when using editform in blazor razor page

查看:53
本文介绍了在blazor razor页面中使用editform时如何重置自定义验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用editcontext的editform:

I have an editform using an editcontext:

    <EditForm OnValidSubmit="HandleValidSubmit" EditContext="_editContext" Context="auth">
      <DataAnnotationsValidator />
      <input type="time" @bind-value="_foodTruck.EndDelivery" @onkeydown="@(q=>ResetValidation("EndDelivery"))" >
        <ValidationMessage For="() => _foodTruck.EndDelivery" />
      <input type="time" @bind-value="_foodTruck.StartDelivery" @onkeydown="@(q=>ResetValidation("StartDelivery"))" >
        <ValidationMessage For="() => _foodTruck.StartDelivery" />
      <input class="btn btn-default" type="submit" value="save" />
    </EditForm>

我在HandleValidSubmit中进行了一些自定义验证:

I do some custom validations in HandleValidSubmit:

EditContext _editContext = new EditContext(_foodTruck);
private async void HandleValidSubmit()
{
  var messageStore = new ValidationMessageStore(_editContext);
  if (_foodTruck.StartDelivery >= _foodTruck.EndDelivery)
  {
    messageStore.Add(_editContext.Field("EndDelivery"), "Bad time entered");
    _editContext.NotifyValidationStateChanged();
  }
 if (!_editContext.Validate()) return;
}

现在发生的是我的自定义错误(输入错误时间")显示在正确的位置.唯一的问题是:更改值后该错误不会消失.因此,如果我单击提交"按钮,就永远不会再次调用HandleValidSubmit.

What now happens is that my custom error ("bad time entered") is displayed at the right position. The only issue is: That error does not disappear when I change the value. So HandleValidSubmit is never called again if I click onto the submit button.

我还尝试在修改字段时清空验证错误:

I also tried emptying the validationerrors when modifying the fields:

   protected void ResetValidation(string field)
    {
        var messageStore = new ValidationMessageStore(_editContext);        
        messageStore.Clear(_editContext.Field(field));
        messageStore.Clear();
        _editContext.NotifyValidationStateChanged();
    }

这由onkeydown调用.但这似乎也没有影响.错误消息不会消失,因此也不会调用HandleValidSubmit.

This is called by onkeydown. But that doesn't seem to have an effect, either. The Errormessage does not disappear and so HandleValidSubmit isn't called either.

推荐答案

我通过在Validation-reset上创建一个新的EditContext来解决此问题.所以我只是将以下行添加到ResetValidation-Method中:

I solved this by creating a new EditContext on Validation-reset. So I simply added the following line to the ResetValidation-Method:

  _editContext = new EditContext(_foodTruck);

但是说实话:那感觉不对.因此,我将保持开放状态,以期获得更好的答案(希望如此).

But to be honest: That does not feel right. So I will leave this open for better answers to come (hopefully).

这篇关于在blazor razor页面中使用editform时如何重置自定义验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆