【问题标题】:Blazor EditForm with custom fluent validator, remove rule while updating带有自定义流利验证器的 Blazor EditForm,在更新时删除规则
【发布时间】:2020-04-07 12:18:39
【问题描述】:

我有自定义验证器

RuleFor(d => d.Id).NotEmpty()
            .Matches("^[0-9]*$")
            .WithMessage("Id must consist of number!")
            .MustAsync(async (id, token) =>
            {
                // make http request

                if (someCase)
                {
                    return false;
                }

                return true;
            }).WithMessage("Some error");

并在 EditForm 中使用它

<FluentValidationValidator ValidatorType=typeof(MyValidator) />

禁用按钮

EditContext = new EditContext(MyModel);
EditContext.OnFieldChanged += async (sender, e) =>
{
   IsInvalidForm = !(await Validator.ValidateAsync(MyModel)).IsValid;
   StateHasChanged();
};

到目前为止一切都很好,它可以工作,但是在更新(使用相同的 Razor 组件)时,Id 字段是禁用,如果我更改验证器的其他值部分,它还会检查 Id并返回 IsValid false(因为它已经存在)。我该如何解决?

【问题讨论】:

    标签: c# asp.net-core blazor fluentvalidation blazor-server-side


    【解决方案1】:

    向您的验证器添加状态应该可以工作

    private bool _isValid;
    RuleFor(d => d.Id).NotEmpty()
                .Matches("^[0-9]*$")
                .WithMessage("Id must consist of number!")
                .MustAsync(async (id, token) =>
                {
                    if (_isValid)
                    {
                       return true;
                    }
                    // make http request
    
                    if (someCase)
                    {
                        return false;
                    }
    
                    _isValid = true;
                    return true;
                }).WithMessage("Some error");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2017-07-25
      • 2016-01-27
      相关资源
      最近更新 更多