views:

748

answers:

2

I'm trying to write my own Custom Validation attribute but i'm having some problems.

The attribute i'm trying to write is that when a user logs in, the password will be compared against the confirmation password.

namespace Data.Attributes
{
public class ComparePassword : ValidationAttribute
{
    public string PasswordToCompareWith { get; set; }

    public override bool IsValid(object value)
    {
        if (PasswordToCompareWith == (string)value)
        {
            return true;
        }
       return false;
    }
}

Now my problem is when i'm trying to set the attribute like this in the model file:

 [Required]
    [ComparePassword(PasswordToCompareWith=ConfirmPassword)]
    public string Password { get; set; }


    [Required]
    public string ConfirmPassword { get; set; }
   }

I get the following error:

Error 1 An object reference is required for the non-static field, method,       or property 'Project.Data.Models.GebruikerRegistreerModel.ConfirmPassword.get'  

It seems that VS is not accepting the confirmpassword in the "PasswordToCompareWith=ConfirmPassword" part

Now my question:

What am i doing wrong?

Thanks in advance!!!

A: 

Sorry to disappoint you but handling such a simple case like yours using Data Annotations could be a pain. You may take a look at this post.

Darin Dimitrov
This will solve my problem! Thanks for the link mate! :)
wh0emPah
A: 

You can't pass a reference type to an attribute unless you do some rather lame reflection code.

In this situation, I would think creating a custom model binder would be a better idea and then checking the Password and ComparePassword at that point.

Tejs
I think that model binder is definitely more lame than using DataAnnotations with reflection. I believe that model binder should not define validation rules.
LukLed
I'm kinda new, Could you explain how reflections work?
wh0emPah
Hah, that's a huge discussion topic. I couldn't properly explain that is this short a space, but I can point you to a good resource: http://msdn.microsoft.com/en-us/library/f7ykdhsy(VS.71).aspx
Tejs
Thanks!! I appreciate your help
wh0emPah