.NET Core | Custom Validation Attributes

Photo by Joshua Sortino on Unsplash

When you have complex model properties, in some cases it requires a specific type of validation, that classical Data annotation attributes cannot provide.
That’s where custom validation attributes could come and smoothen the process of validation without overwhelming the controller on your post back to the server. Today I will walk you through building custom validation attributes to validate file uploads in .NET Core.

1- Creating the model

As you can see I made a simple model and more specifically I have an IFormFile property for the file upload.

2-Creating the Custom Validator

When you make a custom validator class it needs to inherit from the ValidationAttribute base class and, it needs to override the IsValid method so we can perform the operation and check if the values meet the required logic.

3- Adding the Custom attribute to the property.

Since the validation class is inheriting from ValidationAttribute we can specify the tag under the related property.

4- Adding the view and controller methods.



  • Now, by trying to upload a file it will go to the customer attribute and validate the size if it’s within the bounds, alongside checking the file format if it’s (Png, Jpeg). If the result is negative it will show the error on the page below the input.
Photo by Debby Hudson on Unsplash


Custom attributes can ease the process of validating custom business logic without having the validation logic in a class (if the logic is small and doesn't require a class creation).



Connect with me on LinkedIn




Software developer | Programming and Blockchain enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

RecyclerView in Android using Java and Xml

Getting a handle on Gutenberg… slowly.

Strong Data Quality, Strong Data Operations: Our Investment in Toro

Using Audacity for Video Glitch Effects

A day in the life: Ale Paredes (Head of Engineering, Code Climate)

Deep Dive into Modifiers Jetpack Compose

Hackathon Prep with Laravel

10 reasons why software development projects fail

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ibrahim Jaber

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast

More from Medium

Add MVC Controller With Views using Entity Framework in NET 6

An easier way to update the entities’ operators/timestamp in dotnet

Upload Single Or Multiple Files In ASP.Net Core using IFormFile

Wpf.Extensions.Hosting for running WPF on Generic Hosts has been released.