How to manually validate a model with attributes?

前端 未结 4 1366
既然无缘
既然无缘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 14:47

    You can use Validator to accomplish this.

    var context = new ValidationContext(u, serviceProvider: null, items: null);
    var validationResults = new List();
    
    bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
    

提交回复
热议问题