mvc3validation检查属性值是否不同

在MVC3中,您可以向模型添加validation,以检查属性是否匹配如下:

public string NewPassword { get; set; } [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } 

有没有办法检查两个属性是否有所不同,如下面的假设代码?

 [CheckPropertiesDiffer("OldPassword", ErrorMessage = "Old and new passwords cannot be the same")] public string OldPassword { get; set; } public string ConfirmPassword { get; set; } 

以下是您可以在模型中使用的内容:

 public string OldPassword [NotEqualTo("OldPassword", ErrorMessage = "Old and new passwords cannot be the same.")] public string NewPassword { get; set; } 

然后定义以下自定义属性:

 public class NotEqualToAttribute : ValidationAttribute { private const string defaultErrorMessage = "{0} cannot be the same as {1}."; private string otherProperty; public NotEqualToAttribute(string otherProperty) : base(defaultErrorMessage) { if (string.IsNullOrEmpty(otherProperty)) { throw new ArgumentNullException("otherProperty"); } this.otherProperty = otherProperty; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, otherProperty); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty); if (otherPropertyInfo == null) { return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty)); } var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (otherPropertyValue != null && !string.IsNullOrEmpty(otherPropertyValue.ToString())) { if (value.Equals(otherPropertyValue)) { return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); } } } return ValidationResult.Success; } } 

我会检查控制器。

在控制器中:

 if(model.ConfirmPassword == model.OldPassword ){ ModelState.AddModelError("ConfirmPassword", "Old and new passwords cannot be the same"); } 

在视图中:

 @Html.ValidationMessage("ConfirmPassword") 

希望这可以帮助

您还可以在此处的说明中实现类级别validation: http : //weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and -Asp净MVC-3.aspx

基本上,您实现了IValidatableObject的Validate方法,并且可以访问您想要的任何属性。

 public class MyClass : IValidateableObject { public string NewPassword { get; set; } public string OldPassword { get; set; } public IEnumerable Validate(ValidationContext context) { if (NewPassword == OldPassword) yield return new ValidationResult("Passwords should not be the same"); } } 

我不认为已经存在提供此function的内置属性。 最好的方法是创建自己的自定义属性,如下所述: http : //www.codeproject.com/KB/aspnet/CustomValidation.aspx