Ven*_*sky 2 c# data-annotations blazor blazor-server-side blazor-client-side
我EditContext从CascadingParameter
[CascadingParameter]
public EditContext EditContext { get; set; }
Run Code Online (Sandbox Code Playgroud)
我认识一个真实存在的.Validate方法,即验证了整个Model的EditForm。
但我只想验证Model.
谁能只验证Modelfrom 的一个字段EditForm?
如果你想知道为什么我想要这个......是因为我正在制作一个自定义组件,当值发生变化并且它是一个有效值时,它会做一些事情。
在查看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)