I have a question about custom validator allowing multiple attribute I need to display a modal based on DOB. I'm having problems adding data-val properties in AddValidation method is only displaying the properties of the first attribute.
[AgeRange("ModalA", 0, 64, ErrorMessage = "Modal A Error")]
[AgeRange("ModalB", 65, 80, ErrorMessage = "Modal B Error")]
public override DateTime? DateOfBirth { get; set; }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)]
public class AgeRangeAttribute : ValidationAttribute, IClientModelValidator
{
public AgeValidationProperties ValidationProps { get; set; }
public AgeRangeAttribute(string id, int yearMinimum, int yearMaximum)
{
//Init
ValidationProps = new AgeValidationProperties()
{
YearMinimum = yearMinimum,
YearMaximum = yearMaximum,
Id = id
};
}
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
//Logic for Valid
}
public void AddValidation(ClientModelValidationContext context)
{
//UPDATE!!!!
var attributes = context.ModelMetadata.ContainerMetadata
.ModelType.GetProperty(context.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(AgeRangeAttribute), false)
.Cast<AgeRangeAttribute>();
var props = attributes.Select(x => x.ValidationProps).ToList();
var messages = attributes.Select(x => x.ErrorMessage).ToList();
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-agerange", JsonConvert.SerializeObject(messages));
MergeAttribute(context.Attributes, "data-val-agerange-props", JsonConvert.SerializeObject(props));
}
}
public class AgeValidationProperties
{
public int YearMinimum { get; set; }
public int YearMaximum { get; set; }
public string Id { get; set; }
}
I want to validate DOB property based on the rules added in the DataAnnotations decorator if age is lower than 64 years old in client will display ModalA and if age is between 65 and 80 will display ModalB and greater than 80 is a valid date.

