代码来自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
的第二个参数?
请帮忙。感谢
答案 0 :(得分:0)
如果我没有错,它应该是集合(IEnumerable),所以它必须是[]类型。更改为.tostring()不会产生数组。
public ValidationResult(string errorMessage, IEnumerable<string> memberNames);
此外,重载的ctor为模型中的一个或多个字段分配验证错误,如果要省略传递成员名称,我猜错误不会与任何字段相关联,而是与表单相关联。请在这里提及另一个不错的答案Assign ValidationResult to specific field?