具有自定义流利验证器的Blazor EditForm,在更新时删除规则

时间:2020-04-07 12:18:39

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

我有自定义验证器

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 假(因为它已经存在)。我该如何解决?

1 个答案:

答案 0 :(得分:-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");