mvc3验证检查属性值是否不同

时间:2011-12-12 11:35:37

标签: c# asp.net-mvc-3 validation

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

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; }

4 个答案:

答案 0 :(得分:6)

我会检查控制器。

在控制器中:

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

在视图中:

@Html.ValidationMessage("ConfirmPassword")

希望这有帮助

答案 1 :(得分:4)

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

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;
    }        
}

答案 2 :(得分:2)

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

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

public class MyClass : IValidateableObject
{
    public string NewPassword { get; set; } 
    public string OldPassword { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
       if (NewPassword == OldPassword)
          yield return new ValidationResult("Passwords should not be the same");
    }
}

答案 3 :(得分:0)

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