Asp.net MVC 3使用DataAnnotations进行条件验证

时间:2021-03-02 16:36:54

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

我正在使用Asp.net MVC 3,面临数据注释的验证问题如下

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

现在userAddressDetails定义如下

 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.

在编辑视图中,DeliveryLine,Zip依赖于IsDefaultMailingAddress,因为如果IsDefaultMailingAddress为true,则必须提供这些字段,否则请提交表单。

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

用于打开和部分提交我们正在使用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

我们已经尝试过http://andrewtwest.com/2011/01/10/conditional-validation-with-data-annotations-in-asp-net-mvc/ http://blogs.msdn.com/b/simonince/存档/ 2010/06/04 /有条件的验证功能于mvc.aspx

but these validation are fired server side, we need to make it work on client side.

但是这些验证是在服务器方面解决的,我们需要让它在客户端工作。

1 个解决方案

#1


2  

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.

您应该创建自己的自定义ValidationAttribute。如果您想要客户端验证,您的属性应该实现IClientValidatable接口,您应该编写自定义客户端验证器。

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);

#1


2  

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.

您应该创建自己的自定义ValidationAttribute。如果您想要客户端验证,您的属性应该实现IClientValidatable接口,您应该编写自定义客户端验证器。

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);