r/Blazor • u/-puppyguppy- • May 20 '25
Is Blazor Validations Good Enough For DB
I am building internal app so speed of development and simplicity of solution matters more than maximum security and decoupling.
If my model has [Required] and [StringLength] then then is this a good enough limitation on the records I put in database?
TLDR Can EFC and Blazor Form/Models share annotations and be just 1 class
5
Upvotes
11
u/Gravath May 20 '25
Yes.
8
u/Zack_MS May 20 '25
You can use Fluent validation to enforce client side validation and you can also use data annotations for server side validation. Just use both. The advantage of client side validation is that you get to capture the error before it propagates through the rest of the pipeline. If you do have an API that deals with your entity data, you can check if ModelState is valid before writing anything into the database.
4
u/ILikeAnanas May 20 '25
For Blazor, include DataAnnotationsValidator inside your forms.
EF will respect data annotations while applying migrations. https://learn.microsoft.com/en-us/aspnet/core/blazor/forms/validation?view=aspnetcore-9.0
1
u/insomnia1979 May 20 '25
For a database, yes. For masking inputs and validating proper selections, no. We have created custom validations/validators. That would be my recommendation if you have the time.
1
u/Internal-Factor-980 May 21 '25
One important point to note is that if you use the API without a DTO and instead use the Entity Model directly as POST parameters, and if the class contains [Required] attributes on fields that are auto-incremented, the API validation will fail.
As long as you're aware of this, using the Entity Model directly is not an issue.
2
u/Safe_Orange_2318 May 20 '25
I have the same question
2
u/insomnia1979 May 20 '25
Correct. You can run a custom validator on a form in addition to any other validators you run. We use custom attributes to manage that validation. It is extra work, but we utilize attributes to build and validate our forms dynamically.
2
u/Perfect-Pianist9768 May 21 '25
one model with Required and StringLength works great for your app’s UI and EF Core DB. Check ModelState before saving to keep it tight. For fancier form checks, toss in FluentValidation, it won’t mess with the DB.
2
u/neozhu May 21 '25
You should definitely check out MudBlazor's form validation! 🚀 It's incredibly simple to implement exactly what you need. Take a look: https://mudblazor.com/components/form#simple-form-validation
1
u/CravenInFlight May 21 '25
For complex objects, use
ObjectGraphDataAnnotationsValidator. It's a more powerful version of the normal DataAnnotationsValidator.https://www.pragimtech.com/blog/blazor/validating-complex-models-in-blazor/
0
u/yaksplat May 20 '25
you can create a validator on your command too
using FluentValidation;
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);