2

I am using model validation for validating web api requests using:

ActionFilterAttribute

Is it possible for having a validation rule for model's property 'B' which is dependent upon the property 'A'. Consider this example for more clarification

public class ValidationModel
{

    [Required]
    public int? Id { get; set; }

    public string Barcode { get; set; }

    public string BarcodeType { get; set; }
}

The above model has an Id property which is required and Barcode, BarcodeType property which is optional, is it possible to set BarcodeType property to required if and only if there is any value in the Barcode property(if it is not null and an empty string)

Justice
  • 422
  • 2
  • 8
  • 21

2 Answers2

2

There is a built in mechanism for custom validation in MVC that is triggered automatically for posted ViewModels that implement IValidatableObject.

For Example:

public class ValidationModel : IValidatableObject {
    // properties as defined above

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
         if (!string.IsNullOrWhiteSpace(Barcode) && string.IsNullOrWhiteSpace(BarcodeType)) {
             yield new ValidationResult("BarcodeType is required if Barcode is given", new[] { "BarcodeType" });
         }
     }
}

You can check whether the validation was successful in the controller by testing ModelState.IsValid

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • yield new ValidationResult() must be => yield return new ValidationResult(errorMessage: "", memberNames: new[] {""}); –  Dec 10 '20 at 15:19
0

I would check out MVC Foolproof Validation. Its an easy to use package that will provide you with multiple ways to accomplish conditional based model validation. It provides many validators such as:

  • [RequiredIf]

  • [RequiredIfNot]

  • [RequiredIfTrue]

  • [RequiredIfFalse]

  • [RequiredIfEmpty]

  • [RequiredIfNotEmpty]

  • [RequiredIfRegExMatch]

  • [RequiredIfNotRegExMatch]

    It even works with jQuery validation out of the box. http://foolproof.codeplex.com/

Community
  • 1
  • 1
R007
  • 378
  • 4
  • 11