Asp.net mvc 5 自定义必需属性asp.net mvc数据批注
我需要在errormessage中为所需属性插入一个自定义值,如中所示 有一个属性属性 同一实体中还有另一个属性 属性字符串月份 如果未提供WagePayed,则应显示错误消息,请输入1月份支付的工资Asp.net mvc 5 自定义必需属性asp.net mvc数据批注,asp.net-mvc-5,data-annotations,Asp.net Mvc 5,Data Annotations,我需要在errormessage中为所需属性插入一个自定义值,如中所示 有一个属性属性 同一实体中还有另一个属性 属性字符串月份 如果未提供WagePayed,则应显示错误消息,请输入1月份支付的工资 所需的属性是否能够执行此操作,或者应该执行哪些自定义操作来实现此操作我将实现IValidatableObject public class ClassWhichNeedsValidation : IValidatableObject { public string Month {get;
所需的属性是否能够执行此操作,或者应该执行哪些自定义操作来实现此操作我将实现IValidatableObject
public class ClassWhichNeedsValidation : IValidatableObject
{
public string Month {get; set;}
public decimal WagePaid{get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (WagePaid == null)
yeild return new ValidationResult("Please enter the wage paid for the month of January.")
}
}
还需要客户端验证,我认为我们无法将客户端验证与IValidatableObject连接起来,对吗?与验证属性相关联的错误消息是静态的,
jquery validate Untrusive
在首次加载页面时解析它们。您可能需要一个脚本来根据当前月份更改WagePaid
的``data val required`属性,然后重新解析验证器。
[CustomValidation("Month")]
public decimal WagePaid{get; set;}
public class CustomValidationAttribute : ValidationAttribute
{
public CustomAttribute(string month)
{
_month = month;
}
private string _month;
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var property = context.ObjectType.GetProperty(propertyName);
var monthValue = property.GetValue(context.ObjectInstance, null);
if (value == null)
{
return new ValidationResult("Please enter the wage paid for the month of " + monthValue);
}
return null;
}
}