简体   繁体   English

如何在具有多个属性的属性上停止模型验证传播

[英]How to stop model validation propagation on a property with multiple attributes

I have following model in my web api 我的web api中有以下模型

public class MyModel
{
    [Required(ErrorMessage = "Date is required")]
    [ValidDate(ErrorMessage = "Not a valid date format")]
    [ValidStartDate(ErrorMessage = "Not a valid start date")]
    public string startDate { get; set; }


    [Required(ErrorMessage = "Date is required")]
    [ValidDate(ErrorMessage = "Not a valid date format")]
    [IsDateAfterOrOnStartDate("startDate", ErrorMessage = "end date must be greater than or equal to start date")]
    public string endDate { get; set; }

}

I have implemented some custom logic in my custom attributes ValidDateAttribute, ValidStartDateAttribute and IsDateAfterOrOnStartdateAttribute. 我在自定义属性ValidDateAttribute,ValidStartDateAttribute和IsDateAfterOrOnStartdateAttribute中实现了一些自定义逻辑。 But what I want is that if ValidDateAttribute (on both the properties) gives an error or model validation fails on it. 但我想要的是,如果ValidDateAttribute(在两个属性上)给出错误或模型验证失败。 I don't want the framework to execute ValidStartDateAttribute on startDate property and IsDateAfterOrOnStartDateAttribute on endDate property, in other words I want model validation to stop it there itself without further propagating and executing other attributes on these properties. 我不希望框架在startDate属性上执行ValidStartDateAttribute,在endDate属性上执行IsDateAfterOrOnStartDateAttribute,换句话说,我希望模型验证能够自动停止它,而无需在这些属性上进一步传播和执行其他属性。

Is there anyway I can achieve the desired result? 无论如何我能达到预期的效果吗?

Not sure you're going to be able to do what you want exactly, but logically, those other validation attributes just don't make sense if there is not a value or not a valid value. 不确定你是否能够完全按照自己的意愿行事,但从逻辑上讲,如果没有值或没有有效值,那些其他验证属性就没有意义。 So you could fairly easily just have them perform the same checks before adding their own validation error. 因此,在添加自己的验证错误之前,您可以非常轻松地让它们执行相同的检查。 In other words, have ValidDate just not add its error if there is no value, and have IsDateAfterOrOnStartDate not add its error if there is no value or if the value is not a valid date. 换句话说,如果没有值,则ValidDate只是不添加其错误,并且如果没有值或者该值不是有效日期,则IsDateAfterOrOnStartDate不添加其错误。 The end result would be what you want. 最终结果将是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM