.NET Core | Custom Validation Attributes
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.
-Controller
-View
- 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.
Conclusion
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).
Resources
FILE UPLOAD
MODEL VALIDATION
GIT REPO
Connect with me on LinkedIn