Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork91
-
I successfully plugged FluentValidation in a simple Blazor application and everything works fine for basic validation. Imagine we have this classes publicclassPerson{publicstringName{get;set;}}publicclassPersonValidator:AbstractValidator<Person>{PersonValidator(){RuleFor(p=>p.Name).NotEmpty();}} When I submit my form FluentValidation is doing it's job if the Name is empty. My problem is that I have later another rule in my code for exemple Name must be unique in a database. protectedasyncTaskHandleValidSubmit(){try{SavePersonInDb(Person);}catch(NotUniqueExceptione){// How to add a validation error to the Name property ?}} I'm not sure how to add an error to the ModelState and return to the form page. |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Ok, I made some progress based on this blog post :https://www.learmoreseekmore.com/2021/01/blazor-server-forms-validator-component.html I created this component publicclassServerSideValidator:ComponentBase{privateValidationMessageStore_messageStore;[CascadingParameter]publicEditContextCurrentEditContext{get;set;}=null!;protectedoverridevoidOnInitialized(){if(CurrentEditContext==null){thrownewInvalidOperationException("To use validator component your razor page should have the edit component");}_messageStore=newValidationMessageStore(CurrentEditContext);CurrentEditContext.OnValidationRequested+=(s,e)=>_messageStore.Clear();CurrentEditContext.OnFieldChanged+=(s,e)=>_messageStore.Clear(e.FieldIdentifier);}publicvoidDisplayErrors(Dictionary<string,List<string>>errors){foreach(varerrorinerrors){_messageStore.Add(CurrentEditContext.Field(error.Key),error.Value);}CurrentEditContext.NotifyValidationStateChanged();}} I have two validators now : <EditFormModel="@Data"OnValidSubmit="@HandleValidSubmit"> <FluentValidationValidatorDisableAssemblyScanning="@true" /> <ServerSideValidator@ref="serverSideValidator" /></EditForm> And I can add my custom error like this protectedasyncTaskHandleValidSubmit(){try{SavePersonInDb(Person);}catch(NotUniqueExceptione){varerrors=newDictionary<string,List<string>>();errors.Add(nameof(Data.Description),newList<string>{"Testing description"});serverSideValidator.DisplayErrors(errors);}} Now it works, but I'm wondering if there is a more elegant way to do it ? |
BetaWas this translation helpful?Give feedback.