How to manually validate a model with attributes?

前端 未结 4 1360
既然无缘
既然无缘 2020-12-02 14:01

I have a class called User and a property Name

public class User
{
    [Required]
    public string Name { get; set; }
}

4条回答
  •  情歌与酒
    2020-12-02 14:44

    I made an entry in the Stack Overflow Documentation explaining how to do this:

    Validation Context

    Any validation needs a context to give some information about what is being validated. This can include various information such as the object to be validated, some properties, the name to display in the error message, etc.

    ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.
    

    Once the context is created, there are multiple ways of doing validation.

    Validate an Object and All of its Properties

    ICollection results = new List(); // Will contain the results of the validation
    bool isValid = Validator.TryValidateObject(objectToValidate, vc, results, true); // Validates the object and its properties using the previously created context.
    // The variable isValid will be true if everything is valid
    // The results variable contains the results of the validation
    

    Validate a Property of an Object

    ICollection results = new List(); // Will contain the results of the validation
    bool isValid = Validator.TryValidatePropery(objectToValidate.PropertyToValidate, vc, results, true); // Validates the property using the previously created context.
    // The variable isValid will be true if everything is valid
    // The results variable contains the results of the validation
    

    And More

    To learn more about manual validation see:

    • ValidationContext Class Documentation
    • Validator Class Documentation

提交回复
热议问题