Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC 3 Conditional validation with DataAnnotations

I are using Asp.net MVC 3, facing validation problem with dataannotations as below

We have maintained model in separate library project, model class hierarchy is like Below

public class EditAlternateMailingAddressModel : BaseModel
{
    public UserAddressDetails AlternateAddressDetails { get; set; }

    public List<UsState> StateList { get; set; }        
}

now userAddressDetails is defined like below

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

validation logic are defined in separate class like 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 view, DeliveryLine, Zip are dependent on IsDefaultMailingAddress as these fields must be provided if IsDefaultMailingAddress is true, otherwise let form to be submitted.

for opening and partially submitting the forms we are using jQuery.

We 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 these validation are fired server side, we need to make it work on client side.

like image 715
user889937 Avatar asked Aug 11 '11 13:08

user889937


1 Answers

You should create you own custom ValidationAttribute. If you want client validation, your attribute should implement IClientValidatable interface, and you should write custom client side validator.

Updated: added code samples

Implementing validator:

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 validator:

(function ($) {
    $.validator.addMethod('customRequire', function (value, element) {
        // your validation logic here
        return true; // true if valid, otherwise false 
    });
    $.validator.unobtrusive.adapters.add('customRequire');
})(jQuery);
like image 65
hazzik Avatar answered Oct 11 '22 06:10

hazzik