Search code examples
asp.netasp.net-mvcasp.net-mvc-4foolproof-validation

Foolproof multiple validators on the same fields


I currently use foolproof for that validation:

[RequiredIfNot("type", 3, ErrorMessage = "Please enter at least one value")]
public int[] audites { get; set; }

but customer wants to add validation as that:

[RequiredIfNot("type", 3, ErrorMessage = "Please enter at least one value")]
[RequiredIfNot("nature", 1, ErrorMessage = "Please enter at least one value")]
[RequiredIfNot("nature", 3, ErrorMessage = "Please enter at least one value")]
public int[] audites { get; set; }

But it compilator disagree with that, so how can In combine both?

Thanks in advance!


Solution

  • The Foolproof.RequiredIfNotAttribute derives from Foolproof.ModelAwareValidationAttribute (which in turn derives from System.ComponentModel.DataAnnotation.ValidationAttribute). ModelAwareValidationAttribute is marked with [AttributeUsage(AttributeTargets.Property)]. Refer source code. By default the the AllowMultiple parameter of AttributeUsage is false which means that you can only apply the attribute once to a property. You have tried to apply it 3 times, hence the error.

    Having it true and allowing it to be applied multiple times would possibly cause problems in setting the $.validator.methods and $.validator.unobtrusive.adapters functions used by unobtrusive validation.

    You will need to use some other validation attributes or create your own ValidationAtribute that implements IClientValidatable, or rely on server side validation.