如何验证 Blazor EditForm 中的单个字段?

Ven*_*sky 2 c# data-annotations blazor blazor-server-side blazor-client-side

EditContextCascadingParameter

[CascadingParameter]
public EditContext EditContext { get; set; }
Run Code Online (Sandbox Code Playgroud)

我认识一个真实存在的.Validate方法,即验证了整个ModelEditForm

但我只想验证Model.

谁能只验证Modelfrom 的一个字段EditForm

如果你想知道为什么我想要这个......是因为我正在制作一个自定义组件,当值发生变化并且它是一个有效值时,它会做一些事情。

Ven*_*sky 8

在查看Peter Morris Library 时,我发现如果您想验证非复杂字段,您只需要创建一个FieldIdentifierand 调用EditContext.NotifyFieldChanged(fieldIdentifier),它就会触发该字段验证。

所以答案要简单得多:

// Get the FieldIdentifier with the EditContext from the field name
FieldIdentifier fieldIdentifier = EditContext.Field(fieldName);

// Validate the field when notifying change
EditContext.NotifyFieldChanged(fieldIdentifier);

// To check if the field is valid, 
// check if there is any error message. 
return !EditContext.GetValidationMessages(fieldIdentifier).Any();
Run Code Online (Sandbox Code Playgroud)

  • 如果您不想创建新的“FieldIdentifier”实例,还可以调用“EditContext.Field(string fieldName)”方法来获取“FieldIdentifier”。例如,您可以将其写为“EditContext.NotifyFieldChanged(EditContext.Field(fieldName));” (3认同)