Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Everybody,

I have a Model in which have Two Properties that i need to compare and they properties should not equal.

Public class Customer
{
public string NewPassword {get; set;}
public string OldPassword {get; set;}
}

Is there any attribute avalable for same like : Not Compare

Thanks
Posted
Updated 27-Jun-19 10:48am

Go to VS.
Create new project of type MVC Application -> Internet Application.
Then go to Models folder and look at AccountModels.

Are you see this? :

C#
[Required]
[StringLength(100, ErrorMessage = "Value {0} must be greater length than {2} symbols.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("NewPassword", ErrorMessage = "New Password and Confirm Password are not equal.")]
public string ConfirmPassword { get; set; }


How do you like this standart attribute "Compare"?

UPD: Sorry not properly understand you from first time.
 
Share this answer
 
v2
Comments
Anubhava Dimri 2-Jul-13 10:42am    
Hi Denis,

My Requirement is that there is two property OldPassword and NewPassword. and i want the Attribute when OldPassword is not same as NewPassword.

I just want the opposite situation of the Compare.


In your situation OldPassword and NewPassword must be same. but i just want the opposite case.
Denis Shemenko 2-Jul-13 10:46am    
try this: http://weblogs.asp.net/blogs/scottgu/image_71074F19.png
just change the comparison operator for your needs :)
maybe something like this

C#
public class NotEqualAttribute : ValidationAttribute
{
  private string OtherProperty { get; set; }

  public NotEqualAttribute(string otherProperty) 
  {
    OtherProperty = otherProperty;
  }

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    // get other property value
    var otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
    var otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance);
    
    // verify values
    if (value.ToString().Equals(otherValue.ToString()))
      return new ValidationResult(string.Format("{0} should not be equal to {1}.", validationContext.MemberName, OtherProperty));
    else
      return ValidationResult.Success;
  }
}


usage:

C#
[Required]
public string OldPassword { get; set; }
[Required]
[NotEqual("OldPassword")]
public string NewPassword{ get; set; }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900