简体   繁体   中英

How to add a per element validation for en Enumerable in Asp.Net Core?

I have this field that will be mapped from body:

[Required]
public IReadOnlyCollection<long?> Ids { get; set; }

I'd like to add a required attribute (or rather any arbitrary validation attribute) to the element itself (ie I want every element of the array validated).

I could create a class that would have an Id, but then I'll need to pass an array of objects from JSON while I'd like ideally to get an array like that [1,2,3,4] .

Is it possible to do with some trick, I did not manage to figure it out?

You can create a custom attribute which will check for non nulls on an IEnumerable:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class NonNullElementsAttribute : ValidationAttribute{

 public override bool IsValid(object value)
 {
    // cast object to IEnumerable
    // Validate your logic.
 }
}

You can the put this property on top of your element

[Required]
[NonNullElements]
public IReadOnlyCollection<long?> Ids { get; set; }

You can make this even more generic by making it a more generic check on list that validates each element. For example for string types you may want string.IsNullOrWhiteSpace

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