5

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.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176

1 Answers1

22

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();
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • You need reflection if you want to preserve the modified state. – Peter Morris Jul 06 '20 at 21:42
  • 1
    It's possible to validate a complex object without reflection? – Vencovsky Jul 06 '20 at 21:43
  • 7
    If you don't want to create a new isntance of `FieldIdentifier` there is also the `EditContext.Field(string fieldName)` method you can call to get the `FieldIdentifier`. For example you could write it as `EditContext.NotifyFieldChanged(EditContext.Field(fieldName));` – Andy Braham Feb 26 '21 at 05:28