A simple way to validate the data in C#

Vishal Pathak
Abhima C# Programming
2 min readApr 23, 2022

Today we are going to see how we can validate the data in C# without writing too many lines of code. I have seen multiple application where the developer has written too many lines of code for simple validations because of which it increases the project size and slows down the speed of the application.

Hampi

As you know that we have multiple third party frameworks for data validation. But in this article we are not going to install any new external package. In this article we will be using System.ComponentModel.DataAnnotations namespace. In this name space we have multiple attributes which we can use in our model properties directly.

We have following most used and basic validation attributes.

  1. Required:- Ensures property should have value.
  2. StringLength:- Ensures that property value should not cross the max length given in the parenthesis.
  3. EmailAddress:- Ensures value is Email Address.
  4. Phone:- Ensures the value is a phone number.
  5. Compare:- Ensures that values of two properties match as configured in the parenthesis.

And many more….

Below is an example where we have implemented all of the above validation attributes.

In above model class we have multiple properties and above to each property we have used some validation attributes. like Required, EmailAddress, Compare, etc.

Now in the WorkerService class first we have given all the wrong values to trigger each validation. On 41st line we are initializing ValidationContext class against user object. And then in the next line we are initializing List of validationResult. All the validation message will be added in result object during the execution of TryValidateObject function. After TryValidatObject execution we are printing the validation messages. Below is the output.

Model Validation output

As you can see in the above output it is triggering all the validations attributes. The list of validation attributes are not limited you can see the list from the official Microsoft Documentation.

Thank you for reading please comment your suggestions, share the article, follow me and Abhima C# Programming publication.

Bhagavad Gita Verse of the Day

महर्षय: सप्त पूर्वे चत्वारो मनवस्तथा |
मद्भावा मानसा जाता येषां लोक इमा: प्रजा: || 6||

maharṣhayaḥ sapta pūrve chatvāro manavas tathā
mad-bhāvā mānasā jātā yeṣhāṁ loka imāḥ prajāḥ

BG 10.6: The seven great Sages, the four great Saints before them, and the fourteen Manus, are all born from My mind. From them, all the people in the world have descended.

--

--

Vishal Pathak
Abhima C# Programming

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud