[英]How to use a custom annotations validator POCO without any framework (no asp.net, no mvc, no ORM)
我有一個自定義驗證類
using System;
using System.Collections.Generic;
using System.Reflection;
internal class RequiredAttribute1 : Attribute
{
public RequiredAttribute1()
{
}
public void Validate(object o, MemberInfo info, List<string> errors)
{
object value;
switch (info.MemberType)
{
case MemberTypes.Field:
value = ((FieldInfo)info).GetValue(o);
break;
case MemberTypes.Property:
value = ((PropertyInfo)info).GetValue(o, null);
break;
default:
throw new NotImplementedException();
}
if (value is string && string.IsNullOrEmpty(value as string))
{
string error = string.Format("{0} is required", info.Name);
errors.Add(error);
}
}
}
我在以下對象上使用它: -
class Fruit
{
[RequiredAttribute1]
public string Name {get; set;}
[RequiredAttribute1]
public string Description {get; set;}
}
現在,我想在水果列表上運行驗證規則,以打印到字符串
我能想到的是: -
有沒有比這更容易和更內置的東西,用於閱讀這些注釋,而不必添加像(ASP.net / MVC / etc ...)這樣的框架dll?
這僅適用於簡單的控制台應用程序。
我設法使用它
using System.ComponentModel.DataAnnotations;
class RequiredAttribute : ValidationAttribute
{ //... above code }
在主要的Driver類......
using System.ComponentModel.DataAnnotations;
class Driver
{
public static void Main(string[] args)
{
var results = new List<ValidationResult>();
var vc = new ValidationContext(AreaDataRow, null, null);
var errorMessages = new List<string>();
if (!Validator.TryValidateObject(AreaDataRow, vc, results, true))
{
foreach (ValidationResult result in results)
{
if (!string.IsNullOrEmpty(result.ErrorMessage))
{
errorMessages.Add(result.ErrorMessage);
}
}
isError = true;
}
}
}
不需要框架或ORMS,只需要DataAnnotations
庫。
它可以使用多個[屬性]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.