Custom Validation in MVC - Match New Email To Confirmed Email

1.9k views Asked by At

I am trying to create a new custom validation in which I can compare two values within the same class. in this case its checking that when people change their email they have to enter it twice and those two values match. (Would do the same for adding/changing passwords)

    public class CompareAttribute : ValidationAttribute
    {
        public string CompareValue { get; set; }

        public override bool IsValid(string value)
      {
        //we not validating if its required or not!
        if (value == null)
            return true;



        return value.ToLower().Equals(CompareValue.ToLower());
       }
     }

This is my validationattribute class above. I have then tried to use it from within my class doing this

[Compare(CompareValue = newEmail, ErrorMessage = "New email and Confirm email do not match")]

but i get a error on newEmail

Error 3 An object reference is required for the non-static field, method, or property 'BensBoxing.Domain.EmailChange.newEmail.get'

the whole of my class is this

public class EmailChange : Entity
{
    [DisplayName("Current Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "Current Email is a required field")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string currentEmail { get; set; }

    [DisplayName("New Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "New Email is a required field")]
    [EmailInUse(ErrorMessage = "Email is currently in use")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string newEmail { get; set; }

    [DisplayName("Confirm Email Address")]
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "Confirmed Email is a required field")]
    [Compare(CompareValue = newEmail, ErrorMessage = "New email and Confirm email do not match")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
    public virtual string confirmEmail { get; set; }

}
1

There are 1 answers

0
Tib On BEST ANSWER

There are some data annotation extensions that you can use and many more are being worked on currently so you don't have to reinvent the wheel so to speak. Follow the link http://weblogs.asp.net/srkirkland/archive/2011/02/23/introducing-data-annotations-extensions.aspx All you have to do is simply use Nuget to add the extensions to your project and you are ready to use those built in annotations. cheers!