Asp.net MVC 3 Conditional Validation with DataAnnotations

I am using Asp.net MVC 3, faced with data validation problem as below

We saved the model in a separate library project, the model class hierarchy is similar to below

public class EditAlternateMailingAddressModel : BaseModel { public UserAddressDetails AlternateAddressDetails { get; set; } public List<UsState> StateList { get; set; } } 

now userAddressDetails is defined as below

  public partial class UserAddressDetails { public string DeliveryLine { get; set; } public string Zip { get; set; } public bool IsDefaultMailingAddress { get; set; } } 

validation logic is defined in a separate class as shown below

 [MetadataType(typeof(UserAddressDetailsMetaData))] public partial class UserAddressDetails { private class UserAddressDetailsMetaData { [Required(ErrorMessage = "Please enter address.")] public string DeliveryLine { get; set; } [Required(ErrorMessage = "Please enter city.")] public string City { get; set; } public bool IsDefaultMailingAddress { get; set; } 

in edit mode, DeliveryLine, Zip are dependent on IsDefaultMailingAddress, because these fields must be provided if IsDefaultMailingAddress is true, otherwise let the form be submitted.

to open and partially submit forms that we use jQuery.

We have already tried below http://andrewtwest.com/2011/01/10/conditional-validation-with-data-annotations-in-asp-net-mvc/ http://blogs.msdn.com/b/simonince/ archive / 2010/06/04 / conditional-validation-in-mvc.aspx

but this check is performed on the server side, we need to make it work on the client side.

+7
source share
1 answer

You must create your own ValidationAttribute attribute. If you want to check the client, your attribute must implement the IClientValidatable interface, and you must write your own client-side validator.

Updated : code samples added

Validator implementation:

 public class CustomRequiredAttribute : ValidationAttribute, IClientValidatable { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // your validation logic here return ValidationResult.Success; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { return new[] {new CustomRequiredValidationRule (ErrorMessage)}; } } public class CustomRequiredValidationRule : ModelClientValidationRule { public RequiredIfVisibleValidationRule(string errorMessage) { ValidationType = "customRequire"; ErrorMessage = errorMessage; } } 

Adding client-side validation:

 (function ($) { $.validator.addMethod('customRequire', function (value, element) { // your validation logic here return true; // true if valid, otherwise false }); $.validator.unobtrusive.adapters.add('customRequire'); })(jQuery); 
+2
source

All Articles