Data annotations object graph validation is coming to Blazor
Future versions of Blazor will support cascading data annotations support meaning that validation of child components is also supported. First experimental bits were released counted hours ago with .NET Core 3.1 Preview 2. Here’s how object graph validation will work in Blazor.
Building object graph
My previous post about Blazor form validation introduced how validation is implemented for EditForm element used on Blazor pages. The post started with simple GuestbookEntry class. For this post I will use a little bit different guestbook entry and this one has child component.
public class GuestbookEntry
{
[Required]
public Author Author { get; set; }
[Required]
public string Text { get; set; }
public GuestbookEntry()
{
Author = new Author();
}
}
public class Author
{
[Required]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
}
I skip page markup for a moment to show that validation doesn’t work for properties of child component.
Data annotations validation doesn’t support child components out-of-box and this is why name and e-mail fields were not validated.
Introducing experimental object graph validation
.NET Core 3.1 Preview 2 introduces experimental support for object graph validation using data annotations. There’s new form validator called ObjectGraphDataAnnotationsValidator and currently it comes with additional Nuget package:
- Microsoft.AspNetCore.Blazor.DataAnnotations.Validation
We need also one modification to GuestbookEntry class – adding ValidateComplexType attribute to Author property. Without this attribute the validation works only when user leaves the field but not when whole model is validated.
public class GuestbookEntry
{
[Required]
[ValidateComplexType]
public Author Author { get; set; }
[Required]
public string Text { get; set; }
public GuestbookEntry()
{
Author = new Author();
}
}
On page we must replace DataAnnotationsValidator with new ObjectGraphDataAnnotationsValidator.
@page "/"
@using BlazorApp6.Models
<h1>My guestbook</h1>
<p>Leave me a message if you like my site</p>
<EditForm Model="@Model" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
<div class="alert @StatusClass">@StatusMessage</div>
<ObjectGraphDataAnnotationsValidator />
<ValidationSummary />
<div class="form-group">
<label for="name">Name: </label>
<InputText Id="name" Class="form-control" @bind-Value="@Model.Author.Name"></InputText>
<ValidationMessage For="@(() => Model.Author.Name)" />
</div>
<div class="form-group">
<label for="name">E-mail: </label>
<InputText Id="name" Class="form-control" @bind-Value="@Model.Author.Email"></InputText>
<ValidationMessage For="@(() => Model.Author.Email)" />
</div>
<div class="form-group">
<label for="body">Text: </label>
<InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text"></InputTextArea>
<ValidationMessage For="@(() => Model.Text)" />
</div>
<button type="submit">Ok</button>
</EditForm>
@code
{
private string StatusMessage;
private string StatusClass;
private GuestbookEntry Model = new GuestbookEntry();
protected void HandleValidSubmit()
{
StatusClass = "alert-info";
StatusMessage = DateTime.Now + " Handle valid submit";
}
protected void HandleInvalidSubmit()
{
StatusClass = "alert-danger";
StatusMessage = DateTime.Now + " Handle invalid submit";
}
}
After these changes Blazor will validate also properties of Author component like shown on the following screenshot.
As a result validation of our not so primitive view model works perfectly.
NB! There’s also FluentValidation support available for Blazor by Chris Sainty. FluentValidation is powerful and popular validation library. Those familiar with it can use it also in Blazor like they use it in other applications.
Wrapping up
Blazor is making step-by-step its way to be serious application development platform and it’s good to see that product team is working hard on validation too. There are more new validators under construction. Data annotations are popular in .NET world and now Blazor supports also validation of whole object graphs. Although object graph validation is still experimental it’s worth to try it out.
Will this make production any time soon, do you know?
I have no idea how soon it will happen. Next milestone for Blazor is May, this year. Hopefully they will get validation or even somekind of MVVM ready.
How does this work for repeating controls?
For instance, if your name, email, and text were in a control and repeated on the page several times.
Will this work with child components too? My child components actually validate, but don’t display the error message.
I remember some news after writing this post that validation will work over child component trees too. I have not checked yet if and how it works with latest Blazor code. Based on what you wrote it seems to me that there have been some progress and the question is what do you need to change in your code to make child components display error messages.
Why the ‘ObjectGraphDataAnnotationsValidator ‘ solution is Blazor only? I would like it if Microsoft Teams would talk togehter. A web-api-project would benefit from this feature too.
I’m extremely impressed with your writing abilities and also with the structure on your weblog.
Is that this a paid subject or did you customize it your self?
Anyway stay up the excellent high quality writing,
it is rare to see a nice weblog like this one today..
Hey! I realize this is somewhat off-topic but I
needed to ask. Does operating a well-established website such as yours require a lot of work?
I’m completely new to blogging however I do write in my journal every day.
I’d like to start a blog so I can easily share my own experience and thoughts online.
Please let me know if you have any kind of recommendations or tips for new aspiring bloggers.
Thankyou!
Take a look at my web-site – Packaging Machinery
Great information. Lucky me I found your blog by accident
(stumbleupon). I’ve bookmarked it for later!
My family always say that I am killing my time here at net, but
I know I am getting know-how daily by reading such
pleasant articles.
my web-site: Labeling Machine
I was recommended this web site by my cousin. I am not sure whether this
post is written by him as no one else know such detailed about my problem.
You’re amazing! Thanks!
It’s very trouble-free to find out any matter on web as compared to books, as I found this paragraph at this web
site.
I have read so many articles or reviews regarding the blogger lovers but this paragraph is really
a pleasant article, keep it up.
Hello, this weekend is good in favor of me, since this point in time i am reading this fantastic educational paragraph
here at my residence.
You really make it seem so easy with your presentation but I find this topic to be really something
that I think I would never understand. It seems
too complex and very broad for me. I’m looking forward for your next post,
I’ll try to get the hang of it!
Have you ever thought about writing an ebook or guest authoring on other
websites? I have a blog based on the same ideas you discuss and would really
like to have you share some stories/information. I know my audience would enjoy your work.
If you’re even remotely interested, feel free to send me an e mail.
I visited various websites however the audio quality
for audio songs existing at this site is really wonderful.
Every weekend i used to visit this website, because i want enjoyment, as this this web site conations actually nice funny material too.
I simply could not depart your web site before suggesting that I really
enjoyed the usual information an individual supply to your visitors?
Is gonna be again regularly in order to check up on new posts
I must thank you for the efforts you’ve put in penning this website.
I really hope to see the same high-grade content from you later on as well.
In truth, your creative writing abilities has motivated me to get my very own blog now ;)
I loved as much as you will receive carried out right here.
The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get got an shakiness over that you wish be delivering the following.
unwell unquestionably come more formerly again as exactly
the same nearly very often inside case you shield this increase.
Good day! Do you know if they make any plugins to protect
against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Simply wish to say your article is as surprising.
The clearness on your post is simply great and i could
suppose you are knowledgeable in this subject. Well
with your permission let me to seize your
feed to stay up to date with imminent post. Thanks one million and please
continue the gratifying work.
If you want to grow your familiarity just keep visiting
this site and be updated with the latest news update posted here.
We absolutely love your blog and find a lot of your post’s to be what precisely I’m looking for.
Would you offer guest writers to write content for yourself?
I wouldn’t mind composing a post or elaborating on some
of the subjects you write in relation to here. Again, awesome web log!
Thanks for finally talking about > Data annotations object graph validation is coming to Blazor
< Loved it!
Feel free to surf to my homepage … Labeling Machine
whoah this blog is excellent i love reading your articles.
Stay up the good work! You already know, a lot of
individuals are hunting round for this information, you can help them greatly.
Hi outstanding blog! Does running a blog such as this take a
large amount of work? I’ve no expertise in coding however I was hoping to start my own blog soon. Anyways, if you have any
ideas or tips for new blog owners please share. I know this is off subject but I simply wanted
to ask. Many thanks!
Hi there, just wanted to say, I liked this blog post.
It was helpful. Keep on posting!
Hello my friend! I want to say that this article is amazing, great written and come with approximately all
significant infos. I’d like to look extra posts like this .
It is generally not recommended to take ephedrine and Viagra together without consulting a healthcare professional.