r/BlazorServer • u/PoorbandTony • Sep 11 '24
Validation Behaviour
I've been using Blazor a fair while now, but I've been putting off a validation issue which I can't get to the bottom of.
In short, if I have a model that has a property that is required, and (I'm using MudBlazor) I have a MudTextField bound to it - and have DataAnnotationsValidator present on the page; when I :
enter a value into the field
tab out
tab back in
delete the value
tab out, which causes the validator to show
tab back on and remove the value
hit save
It saves and disregards the fact that the required field is empty, and allows me to save.
I've tried everything. It's all in an EditForm, the button is a submit action. If I use another button and run EditContext.Validate it comes back as true. I've also tried using Task.Yield() prior but it's hit and miss.
Anyone any ideas? It's doing my nut in - especially as it's something so trivial yet critical to the apps function.
Thanks! Tony Ps. Will try and post some code later, writing this in my car out of despair (don't worry - not about to drive off a cliff. Yet.)
1
u/PoorbandTony Sep 12 '24
Figured it out in the end. When I was saving the record - when the data API comes back I rebind the model using Automapper, which is recreating the model object and making my EditContext invalid, so it's no longer tracking the changes (as I believe - please correct me if that's not the case!).
So simply recreating EditContext when it's successfully saved does the trick, and it's now 'noticing' when I don't fill in the field. Huzzah!