Blazor Question: How to create reusable components with multiple fields? #54722
Replies: 2 comments
-
Some comments from original poster: https://stackoverflow.com/questions/77491017/validation-within-nested-blazor-components has link to https://gist.github.com/SteveSandersonMS/090145d7511c5190f62a409752c60d00 where @SteveSandersonMS has a possible solution to this problem. But unfortunately, it doesnt work in this scenario (reusable component). The problem seems to be how EditContext?.NotifyFieldChanged(FieldIdentifier); In the child component, the FieldIdentifier for the StreetAddress property becomes I have however discovered that if you call EditorContext.Validate() every time a field changes, then the validation state for the nested fields are updated correctly AND bubbles down to the composite components. The downside is that you get validation errors for all untouched fields. I use this class as a hack for now: public class FluentValidationAllValidator : FluentValidationValidator, IDisposable
{
[CascadingParameter] private EditContext EditContext { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
EditContext.OnFieldChanged += OnFieldChanged;
}
private void OnFieldChanged(object? sender, FieldChangedEventArgs e) => EditContext.Validate();
public void Dispose() => EditContext.OnFieldChanged -= OnFieldChanged;
} |
Beta Was this translation helpful? Give feedback.
-
I don't know if it's exactly what you need, but you might want to look at inheriting from |
Beta Was this translation helpful? Give feedback.
-
I'm having trouble finding a good model for "composit components" in blazor.
Lets say we have a reusable AddressComponent (simplified)
And we have a parent model (simplified - Real world has a model above this with multiple custumers, and customers has multiple addresses)
And customer is shown like this:
Lets say that validation rules are not known to AddressComponent. It could be that address is required if no email has been provided (I'm using FluentValidation for that, and it is working well).
What is working:
What is not working
Other pitfalls:
So how do you get validation to work 100% in a compound component?
Beta Was this translation helpful? Give feedback.
All reactions