ModelValidation

對object進行ModelValidation

適用宣告、轉型、JsonString透過 JsonConvert.DeserializeObject轉型成Object後進行欄位驗證

static void Main(string[] args)
{
	var data = @"{""name"": ""Mark"", ""age"" : 20}";
	var user1 = JsonConvert.DeserializeObject<user>(data);
	var user2 = new user() { name = "Sara", age = 30 };

	var data3 = @"{""name"": ""Ken"", ""age"" : 15}";
	var user3 = JsonConvert.DeserializeObject<user>(data3);
	var user4 = new user() { name = "Pen", age = 13 };

	var result1 = IsModelValid(user1); //false
	var result2 = IsModelValid(user2); //false
	var result3 = IsModelValid(user3); //true
	var result4 = IsModelValid(user4); //true
}

private static bool IsModelValid(object model)
{
	var validationContext = new ValidationContext(model, null, null);
	return Validator.TryValidateObject(model, validationContext, null, true);
}

public class user
{
	[Required]
	[StringLength(3)]
	public string name { get; set; }
	[Range(1, 19)]
	public int age { get; set; }
}

 

 

以上內容,若有錯誤

煩請各路高手路過指正

謝謝!

<(_ _)>