Validation using Attributes in C#

Validation using Attributes in C#

Validating data entered by user can be done via multiple methods. Attributes is one powerful yet simple way to validate input, when working with C#

This code sample describes a user defined Customer and Address classes. As can be seen, some of the properties are annotated with special attributes. These attributes are part of System.ComponentModel.DataAnnotations. Attributes can be placed by the name of the attribute enclosed in square brackets ([]) above the declaration of the entity to which it applies. Here is an example of Attributes used inside Customer and Address classes.

No alt text provided for this image

Upon instantiation of the entity (here done by me, but can be as an input from user), data will be validated against the rules specified in the Attributes.

No alt text provided for this image

All I need to do now, is to fire TryValidateObject method, which takes the newly constructed object (Customer) as an argument, together with Validation Context and a List of Validation result variables. In case user enters, say, First Name as empty, validation will fail and a relevant error message will be shown. Powerful yet simple.

No alt text provided for this image


要查看或添加评论,请登录

Orsan Awawdi的更多文章

  • Docker Disk Space Management

    Docker Disk Space Management

    It is necessary to regularly check the disk space occupied by Docker to ensure efficient resource management and…

  • Code Review

    Code Review

    Code Review is a sensitive matter. It introduces the code you wrote to the eyes of another person, who has their own…

  • re.findall

    re.findall

    When we talk about finding recurrent text in a string, we think about regex (Regular Expressions). Regex has so many…

    1 条评论
  • AI generated code

    AI generated code

    Should we always listen to AI generated code? I asked BLACKBOX.AI to write me a simple code in #python.

  • Environment variables

    Environment variables

    Environment variables are variables that store data in your program but outside your code. For example, key and secret…

    1 条评论
  • Understanding type annotation in Python

    Understanding type annotation in Python

    Why do we need type hints in Python? We can annotate (comment) variables and functions with data types. Being a…

  • Nested Repeaters

    Nested Repeaters

    Let's take an example. We have Categories table in our DB, and each Category has multiple subcategories.

  • Process transcript with Python

    Process transcript with Python

    Let's see what is the most popular word from Donald Trump speech. Transcript of the speech can be found when googling…

  • Three options to filter a list in C#

    Three options to filter a list in C#

    I will show here three different ways to filter text by some string criteria in C#. We have a public class called…