How to validate a single field in Blazor EditForm?

Viewed 5548

I'm getting the EditContext from CascadingParameter

[CascadingParameter]
public EditContext EditContext { get; set; }

And I realized that exists a .Validate method, that validates the entire Model of EditForm.

But I want to validate only one field of the Model.

Who can I validate only one field of the Model from EditForm?

If you are wondering why I want this... Is because I'm making a custom component that when the value changes and it's a valid value, it will do something.

1 Answers

While looking at Peter Morris Library, I found out that if you want to validate non complex fields, you only need to create a FieldIdentifier and call EditContext.NotifyFieldChanged(fieldIdentifier) and it will trigger that field validation.

So the answer is much more simple:

// 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();
Related