Проверка правильности mvc3, если значения свойств отличаются - PullRequest
4 голосов
/ 12 декабря 2011

в 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 ]

6 голосов
/ 12 декабря 2011

Я бы сделал проверку в контроллере.

В контроллере:

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

В представлении:

@Html.ValidationMessage("ConfirmPassword")

Надеюсь, это поможет

4 голосов
/ 12 декабря 2011

Вот что вы можете использовать в модели:

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 голосов
/ 12 декабря 2011

Вы также можете реализовать проверку на уровне класса, как в описании здесь: http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx

По сути, вы реализуете метод Validate объекта IValidatableObject и можете получить доступ к любым свойствам, которые вам нужны.

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");
    }
}
0 голосов
/ 12 декабря 2011

Я не думаю, что уже есть встроенный атрибут, обеспечивающий эту функциональность.Наилучшим подходом было бы создать собственный настраиваемый атрибут, как подробно описано здесь: http://www.codeproject.com/KB/aspnet/CustomValidation.aspx

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...