SoFunction
Updated on 2025-03-06

c# Data annotation and data verification

Data Annotation is a way for a class or class member to add context information. In C#, data annotation is usually described as an Attribute class. Its uses can be divided into the following three categories:

  • Validation: Add verification rules to data
  • Display: Specifies how data is presented to the user
  • Modelling: Add information about usage and relationships with other classes

Here is a Model used to verify and display user information:

class Kid
{
 [Range(0, 18)] // Age cannot be over 18 years old and cannot be negative public int Age { get; set; }

 [StringLength(MaximumLength = 50, MinimumLength = 3)] // The length of the name cannot exceed 50, and cannot be less than 3 public string Name { get; set; }

 [DataType()] // Birthday will be displayed as a date (without time) public DateTime Birthday { get; set; }
}

The display uses of data annotations are mainly used in early frameworks such as MVC. For example, in MVC, the Razor engine dynamically generates different types of form elements based on the DataType attribute of the Model attribute. However, these types of uses are now in addition to WPF (for exampleEditableAttribute) It is outdated and rarely used.

Data annotations are the most common usage. In Core/Mvc, when data is submitted as a form Model, the framework will automatically verify the Model data, or can be called manually.() To determine whether the data is legal.

Custom verification features

Customizing a check feature is simple, creating an inheritanceValidationAttributeclass, then rewrite its class IsValid method. Example:

[AttributeUsage(, AllowMultiple = false, Inherited = false)]
public class EvenNumberAttribute : ValidationAttribute
{
  public override bool IsValid(object input)
  {
    if (input == null)
      return false;

    if (!((), out int val))
      return false;

    return val % 2 == 0;
  }
}

Then this feature can be used like this:

public class Model
{
  [EvenNumberAttribute(ErrorMessage = "The number must be an even number")]
  public int MyNumber { get; set; }
}

In addition to this custom verification method, C# also provides aCustomValidationFeatures are also used to customize data verification, and they are implemented through reflection. Example:

public class Model
{
  [CustomValidation(typeof(MyCustomValidation), "IsNotEvenNumber")]
  public int MyNumber { get; set; }
}

public static class MyCustomValidation
{
  public static ValidationResult IsNotEvenNumber(object input)
  {
    var result = new ValidationResult("The number must be an even number");
    if (input == null || !((), out int val))
      return result;
    return val % 2 == 0 ?  : result;
  }
}

C# has built-in many commonly used data verification features, such as the most commonly used onesRequiredAttributeStringLengthAttributeRangeAttributewait.

Perform data verification manually

Most of the time, data verification is done by frameworks (such as Core) for us, but sometimes how do we do it by manually performing verification data? Simply put, use Validator Class is enough, but it is not as direct as imagined. Data verification requires the verification information, such as verification rules, attributes that need verification, and error information that fails to be displayed, etc. These need to be extracted from the instance to be verified as context, which isValidationContext, so you need to create it firstValidationContext Object:

ValidationContext vc = new ValidationContext(objectToValidate);

Create this context object to verify the data in various ways, such as checking all properties of the object:

ValidationContext vc = new ValidationContext(objectToValidate);
ICollection<ValidationResult> results = new List<ValidationResult>();
bool isValid = (objectToValidate, vc, results, true);

You can also verify only the specified properties of the object:

ValidationContext vc = new ValidationContext(objectToValidate);
ICollection<ValidationResult> results = new List<ValidationResult>();
bool isValid = (, vc, results, true);

The return value isValid indicates whether all data has been verified and the information that failed will be placed in the results result set.

Seeing this, I think it's still a bit troublesome to perform the verification manually.ValidationContext If the object step is also encapsulated in Validator Isn’t it more concise within the class method?

Author: Exquisite Coder

Source: /willick

connect:@

The above is the detailed content of C# data annotation and data verification. For more information about C# data annotation and data verification, please pay attention to my other related articles!