Justice
Justice

Reputation: 442

Model Validation in asp.net Web API with dependent properties

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)

Upvotes: 2

Views: 1054

Answers (2)

R007
R007

Reputation: 388

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/

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

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

Upvotes: 2

Related Questions