11

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.

asked Jul 6, 2020 at 12:14

1 Answer 1

31

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();
answered Jul 6, 2020 at 18:14
Sign up to request clarification or add additional context in comments.

3 Comments

You need reflection if you want to preserve the modified state.
It's possible to validate a complex object without reflection?
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));

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.