ASP.NET MVC 3数据注释:动态添加验证 [英] ASP.NET MVC 3 Data Annotation: Add validation dynamically
本文介绍了ASP.NET MVC 3数据注释:动态添加验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个例子:
public class ProfileViewModel
{
[必需(ErrorMessage =需要字段{0})]
[Display(Name = 客户端代码)]
public int ClientCode {get;组; }
[必需(ErrorMessage =需要字段{0})]
[StringLength(100,ErrorMessage =字段{0}最多可以有100个字符。 )]
[Display(Name =Company)]
public string Company {get;组; }
[StringLength(50,ErrorMessage =字段{0}最多可以包含50个字符。)]
[Display(Name =Name)]
public string Name {get;组; }
[StringLength(50,ErrorMessage =字段{0}最多可以有50个字符。)]
[Display(Name =LastName)]
public string LastName {get;组;
public ProfileViewModel(User usr)
{
if(usuario.ClientCode!= null)
{
ClientCode = Convert.ToInt32(usr。 ClientCode);
}
else
{
//尚未要求ClientCode和Company。
//现在需要Name和LastName。
}
公司= usr.Company;
Name = usr.Name;
LastName = usr.LastName;
}
}
解决方案
认为最简单的做法就是实现 IValidatableObject
:
public class Product:IValidatableObject
{
public int Prop1 {get;组; }
public int Prop2 {get;组; }
public IEnumerable&ValidationResult>验证(ValidationContext validationContext)
{
if(Prop1< Prop2)
yield返回新的ValidationResult(Property 1不能小于Property 2);
}
}
I'm new with data annotation. I'd like to know if it possible (and how) to add some validation dynamically. It is very extensive to explain why, but I've a ViewModel that receives and object when created. In that object I must check for some property and depending its value I should have or not some validations.
An example:
public class ProfileViewModel
{
[Required(ErrorMessage = "The field {0} is required")]
[Display(Name = "Client Code")]
public int ClientCode { get; set; }
[Required(ErrorMessage = "The field {0} is required")]
[StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
[Display(Name = "Company")]
public string Company { get; set; }
[StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
[Display(Name = "LastName")]
public string LastName { get; set; }
public ProfileViewModel(User usr)
{
if (usuario.ClientCode != null)
{
ClientCode = Convert.ToInt32(usr.ClientCode);
}
else
{
//ClientCode and Company are not yet required.
//Name and LastName are now required.
}
Company = usr.Company;
Name = usr.Name;
LastName = usr.LastName;
}
}
解决方案
I think that the simplest way of doing what I wanted is implementing IValidatableObject
:
public class Product : IValidatableObject
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Prop1 < Prop2)
yield return new ValidationResult("Property 1 can't be less than Property 2");
}
}
See also: Class-Level Model Validation with ... ASP.NET MVC 3
这篇关于ASP.NET MVC 3数据注释:动态添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文