【发布时间】:2016-07-05 09:47:40
【问题描述】:
代码取自http://www.dotnetcurry.com/aspnet-mvc/1083/aspnet-mvc-self-validation-model-objects
public class Person : IValidatableObject
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Address { get; set; }
[Required]
public DateTime BirthDate { get; set; }
[Required]
public int Income { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var pIncome = new[] { "Income" };
if (Income < 0)
{
yield return new ValidationResult("Income cannot be negative", pIncome);
}
var pName = new[] { "Name" };
if (Name.Length > 40)
{
yield return new ValidationResult("Name cannot be such huge in length", pName);
}
var pBDate = new[] { "BirthDate" };
if (BirthDate > DateTime.Now)
{
yield return new ValidationResult("Sorry Future Date cannot be accepted.", pBDate);
}
}
}
看到这一行
yield return new ValidationResult("Income cannot be negative", pIncome);
如果我这样写
yield return new ValidationResult("Income cannot be negative", Income.ToString());
然后得到错误但是当我们传递一个字符串变量时就没有问题了。所以如果我需要验证许多 int 类型的属性,那么我需要将这些属性名称放入
string array like var pIncome = new[] { "Income" }; ?
如果数组中有很多元素名称,那么如何将其引用为ValidationResult ctor 的第二个参数?
请帮忙。谢谢
【问题讨论】:
标签: asp.net-mvc-5