如何在ASP.NET MVC中应用条件验证“如果另一个属性为空,则必需”?

时间:2013-01-31 17:46:20

标签: asp.net-mvc validation model conditional

是否有方法可以为virtualPassword属性实现必需的属性,但条件是Password为空?

这是我的代码。

[DataType(DataType.Password)]
[LocalizedDisplayName("UserPassword", NameResourceType = typeof(Languages.Names))]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Languages.Validations))]        
public string Password { get; set; }

private string _virtualPassword = null;
[NotMapped]
[DataType(DataType.Password)]
[LocalizedDisplayName("UserPassword", NameResourceType = typeof(Languages.Names))]
[StringLength(12, MinimumLength = 6, ErrorMessageResourceName = "StringLengthBetween", ErrorMessageResourceType = typeof(Languages.Validations))]
public virtual string virtualPassword { get { return _virtualPassword; } set { _virtualPassword = value; } }

1 个答案:

答案 0 :(得分:0)

您可以通过在模型中实现IValidatableObject来实现自定义验证。

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var issues = new List<ValidationResult>();
if(issue_exist_in_model) //implement whatever condition is applicable
{
    issues.Add(new ValidationResult("Message for issur that exist"));
}

  return issues;
}