访问其他模型属性的自定义验证方法

Joh*_*ean 1 c# validation asp.net-mvc entity-framework

我正在尝试为我的实体之一创建自定义验证方法,因此我创建了一个继承自的类ValidationAttribute

public class OneWheelchairPerTrainAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // This is where I need to access the other entity property
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在努力解决的是如何访问实体上的其他属性。这是我的实体:

public class Ticket
{
    public int Id { get; set; }

    [Required]
    public int TimetableId { get; set; }

    [Required]
    public bool Wheelchair { get; set; }

    public virtual Timetable Timetable { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在编写的验证注释将应用于该Wheelchair属性,并且我需要TimetableId从我的验证方法中访问该属性。

Nic*_* N. 5

另一种(在我看来,更好的)验证多个属性的方法是在class级别上进行。

这与您的答案中的情况不完全相同,但它仍然涉及多个属性验证。

想象一下,你想让轮椅成为一个 id 或一个新对象,但你仍然只想允许一个:

我的ExactlyOneRequired属性的一个例子:

[AttributeUsage(AttributeTargets.Class)]
public class ExactlyOneRequiredAttribute : ValidationAttribute
{
    public string FirstPropertyName { get; set; }
    public string SecondPropertyName { get; set; }

    //Constructor to take in the property names that are supposed to be checked
    public ExactlyOneRequiredAttribute(string firstPropertyName, string secondPropertyName)
    {
        FirstPropertyName = firstPropertyName;
        SecondPropertyName = secondPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null) 
           return new ValidationResult("Object must have a value;");

        var neededProperties = validationContext.ObjectType.GetProperties().Where(propertyInfo => propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName).Take(2).ToArray();
        var value1 = neededProperties[0].GetValue(value);
        var value2 = neededProperties[1].GetValue(value);

        if (value1 == null | value2 == null)
            return ValidationResult.Success;

        return FailedValidationResult();
    }

    public override string FormatErrorMessage(string name) => $"One of the fields: '{FirstPropertyName} or {SecondPropertyName}' is required, it is not allowed to set both.";

    private ValidationResult FailedValidationResult() => new ValidationResult(FormatErrorMessage(FirstPropertyName), new List<string> {FirstPropertyName, SecondPropertyName});
}
Run Code Online (Sandbox Code Playgroud)

用法:

[ExactlyOneRequired(nameof(WheelChairId), nameof(WheelChair))]
public class Train
{
    public int? WheelChairId { get; set; }

    public WheelChair WheelChair { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您当然可以根据需要获得尽可能多的属性,并根据需要使其成为通用的。我的观点是,不是对属性中的属性名称进行字符串检查,而是注入属性名称是更简洁的方法,