mvc3 validation check if property values differ

2019-05-06 05:58发布

问题:

in MVC3 you can add validation to models to check if properties match like so:

public string NewPassword { get; set; }

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

Is there a way to check that two properties differ like in the following make-believe code?

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

public string ConfirmPassword { get; set; }

回答1:

Here is what you could use in the model:

public string OldPassword

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

And then define the following custom attribute:

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:

I would do checking in the controller.

In controller:

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

In View:

@Html.ValidationMessage("ConfirmPassword")

Hope this helps



回答3:

You could also implement class level validation like in the description here: http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx

Basically you implement the Validate method of IValidatableObject and can access any properties you want.

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


回答4:

I don't think that there is already a built-in attribute providing this functionality. The best approach would be to create your own custom attribute like described in detail there: http://www.codeproject.com/KB/aspnet/CustomValidation.aspx