C# 自定义特性属性 限制自定义字段 数据
不知道怎么表达这个东西,先记录一下吧,如果你们有好的想法可以联系我,共同进步
/// <summary>
/// 自定义属性帮助类
/// </summary>
public class AttributeHelper
{
/// <summary>
/// 获取字符串字节长度
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int StringToByteLength(string str)
{
//使用Unicode编码的方式将字符串转换为字节数组,它将所有字符串(包括英文中文)全部以2个字节存储
byte[] bytestr = System.Text.Encoding.UTF8.GetBytes(str);
int j = 0;
for (int i = 0; i < bytestr.GetLength(0); i++)
{
//取余2是因为字节数组中所有的双数下标的元素都是unicode字符的第一个字节
if (i % 2 == 0)
{
j++;
}
else
{
//单数下标都是字符的第2个字节,如果一个字符第2个字节为0,则代表该Unicode字符是英文字符,否则为中文字符
if (bytestr[i] > 0)
{
j++;
}
}
}
return j;
}
/// <summary>
/// 验证字段属性
/// </summary>
public void Validate()
{
ValidationContext context = new ValidationContext(this, serviceProvider: null, items: null);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (isValid == false)
{
StringBuilder sbrErrors = new StringBuilder();
foreach (var validationResult in results)
{
sbrErrors.AppendLine(validationResult.ErrorMessage);
}
throw new ValidationException(sbrErrors.ToString());
}
}
/// <summary>
/// 判断字符串字节长度
/// </summary>
public class IsByteLength : ValidationAttribute
{
public IsByteLength(string errorMsg, int len)
{
this.ErrorMsg = errorMsg;
this.Len = len;
}
public string ErrorMsg { get; private set; }
public int Len { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value.GetType().Equals(typeof(string)))
{
if (StringToByteLength(value.ToString()) > Len)
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
return null;
}
}
public static string ObjToString( object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
public class IsFieldVereist : ValidationAttribute
{
public string ErrorMsg { get; private set; }
public string TypeName { get; private set; }
public IsFieldVereist(string errorMsg, string typeName="")
{
this.ErrorMsg = errorMsg;
this.TypeName = typeName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!string.IsNullOrWhiteSpace(TypeName))
{
var tempData = Convert.ChangeType(validationContext.ObjectInstance, validationContext.ObjectType);
System.Reflection.PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(TypeName);
if (value != null || !string.IsNullOrWhiteSpace(ObjToString(value)))
{
if (propertyInfo.GetValue(tempData, null) == null)
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
}
else
{
if (value == null || string.IsNullOrWhiteSpace(ObjToString(value)))
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
return null;
}
}
}