.NET Manual Model Validation

2022年7月20日 2154点热度 2人点赞 0条评论
内容目录

When not using ASP.NET Core and without the FluentValidation framework, model validation can be implemented through the native API.

public class A
{
	[EmailAddress]
	public string B { get; set; }
}
void Main()
{
	var result = new List<ValidationResult>();
	var a = new A
	{
		B = "aa.com"
	};

	var validationContext = new ValidationContext(a);
	Console.WriteLine(Validator.TryValidateObject(a, validationContext, result, true));
	result.All(x =>
	{
		Console.WriteLine($"{x.MemberNames.First()}:{x.ErrorMessage}");
		return true;
	}
	);
}

file

痴者工良

高级程序员劝退师

文章评论