簡體   English   中英

Blazor 帶有自定義流式驗證器的 EditForm,更新時刪除規則

[英]Blazor EditForm with custom fluent validator, remove rule while updating

我有自定義驗證器

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(因為它已經存在) . 我該如何解決?

將 state 添加到您的驗證器應該可以工作

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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM