参考Model Validation,我发现使用属性验证模型非常容易。我希望能够验证其他项目模板(例如,控制台应用程序,功能应用程序,Xamarin应用程序和桌面应用程序)中的类的模型/对象,这些模板/模板没有对MVC的丰富支持,并且默认情况下没有System.ComponentModel.DataAnnotations。 ValidationAttribute类。
下面是我的Model类:
public class User
{
[Unique]//Ensures that the ID is unique
[AlphaNumeric]//Ensures that the ID is alphanumeric
public string ID { get; set; }
//Custom attribute to determine of the name is valid by concatenating the FirstName and LastName
public string FirstName { get; set; }
public string LastName { get; set; }
[CompanyEmail]//Custom attribute to ensure that validates that the email belongs to the company
public string Email { get; set; }
[CountryPhoneNumber]//Custom attribute to ensure that the phone number belongs to a specific country
public string PhoneNumber { get; set; }
[Age]//Custom attribute to ensure that from the Date of birth, only the users above a certain age can be registered
public DateTime DateOfBirth { get; set; }
}
我需要帮助实现所有属性,因为它们是自定义的,以实现具有如下功能的功能
public static class Validator
{
public static (bool IsValid, List<string> errors) ValidateModel<T>(T obj)
{
//Implementation of the validator that validates the model of Type T in this case User
}
}
我可以按照以下格式致电以获取响应,以后可以在下面使用该响应,如下所示:
public class Program
{
static void Main(string[] args)
{
var response = Validator.ValidateModel<User>(new User
{
DateOfBirth = DateTime.UtcNow.AddYears(-10),
Email = "randomemail@gmail.com",
FirstName = null,
LastName = "",
ID = "!2sunjsd)9(",
PhoneNumber = "27778596829"
});
}
}
对于这种原因,我将不胜感激/提供建议