FluentValidation触发表单中每个字段的验证



因此,在我的Blazor Server应用程序中,我为单个input组件添加了FluentValidation,这很好。我的下一个任务是触发表单中所有组件的验证规则。目前,规则是在用户仅与输入的组件交互时触发的,我还想在用户单击表单上的提交按钮时触发这些相同的规则。

TextField组件:

public partial class TextField
{
ValidationResult Validation = new ValidationResult();
[Parameter]
public AbstractValidator<TextField> Rules { get; set; } = null;
public void Validate()
{
Validation = Rules.Validate(this);
}
private void OnInputEvent(ChangeEventArgs changeEvent)
{
Value = (string)changeEvent.Value;
if (Rules != null)
{
Validate();
}

}
private void OnInputEvent(FocusEventArgs changeEvent)
{
if (Rules != null)
{
Validate();
}
}
}

登录页面:

<TextField class="mb-3" Name="User Name" Width="190px" Rules="UsernameRules" spellcheck="false" />
<TextField class="mb-3" Name="Password" Width="190px" type="password" />
<Button class="text-light" Height="30px" Width="260px" Color="--accent" @onclick="Validate">Log In</Button>

登录页面代码:

public partial class Login
{
private async void Validate()
{
<------------ HOW DO I TRIGGER ALL THE RULES FOR EACH TEXTFIELD COMPONENT?? -------------
}
UsernameValidation UsernameRules = new UsernameValidation();
private class UsernameValidation : AbstractValidator<TextField>
{
public UsernameValidation()
{
RuleFor(field => field.Value)
.NotEmpty().WithMessage("Please enter a username");
}
}
}

只要使用EditForm,您只需要将编辑表单操作链接到OnValidSubmit。您当前可能正在链接到绕过运行_editContext.Validate()OnSubmit

以下是EditForm:的相关代码

private async Task HandleSubmitAsync()
{
Debug.Assert(_editContext != null);
if (OnSubmit.HasDelegate)
{
// When using OnSubmit, the developer takes control of the validation lifecycle
await OnSubmit.InvokeAsync(_editContext);
}
else
{
// Otherwise, the system implicitly runs validation on form submission
var isValid = _editContext.Validate(); // This will likely become ValidateAsync later
if (isValid && OnValidSubmit.HasDelegate)
{
await OnValidSubmit.InvokeAsync(_editContext);
}
if (!isValid && OnInvalidSubmit.HasDelegate)
{
await OnInvalidSubmit.InvokeAsync(_editContext);
}
}
}

相关内容

  • 没有找到相关文章