.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

Kotlin Multiplatform. Practical multithreading (part 2)

.Net Core Model Binders

Kubernetes on Devstack part 1: Deploying the Devstack cloud

Getting Started with LEMP: Installing Nginx, MySQL, PHP on Ubuntu 18.04 (Part 2 of 3)

Integrados a color

Going to the Backend??

CSSConf EU 2019 in a short opinionated recap

Adding a simple search bar

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

.NET 6 Web APIs with OpenAPI TypeScript Client Generation

Blazor with Auth0, using the Management API

Fixing my BF1942 woes with Win32 APIs

Multi-Language with .Net 6