0

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 (i.e. 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?

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • you could add something like this, [Required, MinLength(1, ErrorMessage = "At least one id is required")]]. Or you could write custom validator expanding ValidationAttribute attribute, also you have nullable, is null a valid value? – Nonik Dec 03 '20 at 18:02
  • I can have such validation, but I think you misunderstood, I'll edit question to be more clear, I'd like validation per element – Ilya Chernomordik Dec 03 '20 at 18:24

1 Answers1

0

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

A_kat
  • 1,459
  • 10
  • 17
  • Thanks for the response, I know I can do this custom attribute and check what I need. I do though already have custom attributes operating on long and would rather reuse that logic. – Ilya Chernomordik Dec 03 '20 at 21:22
  • @IlyaChernomordik This not possible unfortunately and this complex scenario is the reason why many people move away from attributes and to solution like FluentValidation which can support those complex scenarios – A_kat Dec 04 '20 at 01:37
  • Yes, I try to as much as possible stick to attributes, but I see the limitation. So I may be forced to switch to fluent... – Ilya Chernomordik Dec 04 '20 at 08:16