csharp 用于测试数据的验证属性晚于另一个
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用于测试数据的验证属性晚于另一个相关的知识,希望对你有一定的参考价值。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessageFormatString = "The {0} field is required.";
public string OtherProperty { get; private set; }
public DateGreaterThanAttribute(string otherProperty)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}
OtherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, OtherProperty);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//Get PropertyInfo Object && Get Value of the property
var basePropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
var basePropertyValue = basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
if(value == null || basePropertyValue == null)
{
return null;
}
DateTime startDate = new DateTime();
DateTime thisDate = new DateTime();
try
{
startDate = (DateTime)basePropertyValue;
thisDate = (DateTime)value;
}
catch(Exception e)
{
var startSplit = basePropertyValue.ToString().Split('/');
startDate = new DateTime(Convert.ToInt32(startSplit[2]), Convert.ToInt32(startSplit[1]), Convert.ToInt32(startSplit[0]));
var thisSplit = value.ToString().Split('/');
thisDate = new DateTime(Convert.ToInt32(thisSplit[2]), Convert.ToInt32(thisSplit[1]), Convert.ToInt32(thisSplit[0]));
}
//Actual comparision
if (thisDate <= startDate)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//Default return - This means there were no validation error
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
//This string identifies which Javascript function to be executed to validate this
rule.ValidationType = "dategreaterthan";
rule.ValidationParameters.Add("other", OtherProperty);
yield return rule;
}
}
以上是关于csharp 用于测试数据的验证属性晚于另一个的主要内容,如果未能解决你的问题,请参考以下文章
csharp 数据注释属性,用于验证字符串是否为有效的XML
csharp 验证属性,用于确保输入的最小位数
csharp 验证可用于web api的AntiForgery令牌属性
表单输入验证,仅允许存在于另一个表中的值 - Access
如何使用ZF2中的数组表单设置使字段验证依赖于另一个字段?
验证码登陆中session加载晚于jsp解决办法