c# - Validating property value, based on another model property -
i have question regarding property validation, however, haven't yet been able find appropriate answer.
i have following classes
public class indexviewmodel { public film film { get; set; } public reviewmodel review { get; set; } } public class reviewmodel { [requiredif // fire if 'genre' equal genre.horror] public string text { get; set; } } public class film { public string title { get; set; } public director director { get; set; } public genre genre { get; set; } } public class director { public string name { get; set; } } public enum genre { horror, thriller, scifi, drama }
is possible add [requiredif]
attribute on text
property in reviewmodel
fires validation based on value of genre
in film
model. appreciated.
i wouldn't recommend using validation attributes when properties need validated aren't in class it's associated with. haven't seen requiredifattribute
implementation cuts across models that. (here's 1 different question.)
what simple implementation of ivalidatableobject
? quite clear, , mvc check when constructing model.
public class indexviewmodel : ivalidatableobject { public film film { get; set; } public reviewmodel review { get; set; } public ienumerable<validationresult> validate(validationcontext validationcontext) { if (film.genre == genre.horror && string.isnullorwhitespace(review.text)) { yield return new validationresult( "please provide review film.", new string[] { nameof(review.text) }); } } }
Comments
Post a Comment