自定义必需属性asp.net mvc数据注释

时间:2015-01-25 15:51:03

标签: asp.net-mvc-5 data-annotations

我需要在所需属性的errormessage中插入自定义值,如

有一个属性属性decimal WagePaid

并且同一实体中还有另一个属性     属性字符串月

然后,当没有提供WagePaid时的错误信息应该是,请输入1月份支付的工资。

必需属性是否能够执行此操作或应该执行哪些自定义来实现此

1 个答案:

答案 0 :(得分:0)

我会实现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.")
    }
}

或者您可以编写自定义验证属性并将其应用于所需的属性,如下所示:

[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;
    }
}