[C#.NET Supplements and omissions] 09: Data labeling and data verification

Data Annotation is a way to add contextual information to a class or class member. It is usually described by an Attribute class in C#. Its use can be divided into the following three categories:

  • Validation: add validation rules to the data

  • Display: Specify how the data is presented to the user

  • Modelling: add information about usage and relationships with other classes

The following is a Model used to verify and display user information:

class Kid
{
  [Range(0, 18)] // 年龄不能超过18岁,不能为负数
  public int Age { get; set; }

  [StringLength(MaximumLength = 50, MinimumLength = 3)] // 名称的长度不能超过 50,不能小于 3
  public string Name { get; set; }

  [DataType(DataType.Date)] // 生日将作为日期展示 (不带时间)
  public DateTime Birthday { get; set; }
}

The use of data annotation is mainly used in early ASP.NET and ASP.NET MVC frameworks. For example, in ASP.NET MVC, the Razor engine dynamically generates different types of form elements based on the DataType feature of the Model attribute. However, this type of use is EditableAttributerarely used except for WPF (for example ) which is outdated.

Data labeling to verify the legitimacy of the data is the most common usage in ASP.NET Core / Mvc, the data submitted as a form Model, Model framework will automatically check the data, you can manually call ModelState.IsValid()to determine whether the data is valid .

Custom calibration feature

Custom verify features a very simple, create an inherited ValidationAttributeclass and override its IsValidmethods. Example:

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

        if (!int.TryParse(input.ToString(), out int val))
            return false;

        return val % 2 == 0;
    }
}

Then this feature can be used like this:

public class Model
{
    [EvenNumberAttribute(ErrorMessage = "数字必须是偶数")]
    public int MyNumber { get; set; }
}

In addition to this embodiment custom check, C # also provides a CustomValidationfeature is used to customize the data checking, which is implemented by way of 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("数字必须是偶数");
        if (input == null || !int.TryParse(input.ToString(), out int val))
            return result;
        return val % 2 == 0 ? ValidationResult.Success : result;
    }
}

C # built many characteristics common data type checking, such as the most commonly used RequiredAttribute, StringLengthAttribute, RangeAttributeand the like.

Perform data verification manually

Most of the time, the data verification is done by the framework (such as ASP.NET Core) for us, but sometimes we want to manually verify the data, how to do it? Simply put, the use of Validatorclass can be, but is not imagine so directly. Data verification needs to provide verification information, such as verification rules, attributes that need to be verified, and error messages that fail to display, etc., and these need to be extracted from the instance to be verified as a context by another class, which is ValidationContext, so we need to create ValidationContextan object:

ValidationContext vc = new ValidationContext(objectToValidate);

After creating this context object, you can verify the data in multiple ways, such as verifying all the attributes of the object:

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

It is also possible to verify only the specified attributes of the object:

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

The return value isValid indicates whether all data has passed the verification, and the information about the verification failure will be placed in the results result set.

See this, I think it is still performed manually check a little trouble, create ValidationContextan object if this step is also encapsulated in the Validatorinner class methods, some of it not simple?

-

Exquisite Coder

Bring you insight into programming and architecture

↑Long press the picture to identify the QR code to follow, don’t miss the fate of the Nethai encounter

Guess you like

Origin blog.csdn.net/sD7O95O/article/details/108860062