Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Custom error coming from business layers#114

Unanswered
juchom asked this question inQ&A
Discussion options

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.

You must be logged in to vote

Replies: 1 comment

Comment options

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 ?

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
1 participant
@juchom

[8]ページ先頭

©2009-2025 Movatter.jp