简体   繁体   中英

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

I have following model in my 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. But what I want is that if ValidDateAttribute (on both the properties) gives an error or model validation fails on it. 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.

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. The end result would be what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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