title: Custom attribute to validate if mail is unique in asp.net mvc
body: <p>I have the following model</p>
  
  <pre><code>public partial class OwnerData
  {
      public string firstname { get; set; }
      public string lastname { get; set; }
  
      [Required]
      [StringLength(60)]
      [EmailAddress]
      [MailNotExists] //this is a custom function
      public string email { get; set; }
  }
  </code></pre>
  
  <p>the custom function <strong>MailNotExists</strong> is the following</p>
  
  <pre><code>namespace MyApp.CustomDataAnnotations
  {
      public class MailNotExists : ValidationAttribute
      {
          protected override ValidationResult IsValid(object value, ValidationContext validationContext)
          {
              DbContext db = new DbContext ();
  
              var user = db.Users.FirstOrDefault(u =&gt; u.email == (string)value);
  
              if (user == null)
                  return ValidationResult.Success;
              else
                  return new ValidationResult("Mail already exists");
          }
      }
  }
  </code></pre>
  
  <p>The model is used into the view to give the user the possibility to change his mail, trough</p>
  
  <pre><code> @Html.EditorForModel();
  </code></pre>
  
  <p>The html output returns into the editor also the already existing mail, if you want to change it the system first check if the mail is already present in the db trough the validator <strong>[MailNotExists]</strong> and everything is ok. The only problem is that if the user don't want to change the mail but only the firstname or lastname and then submit the form the validator returns an error because the mail already exists.</p>
  
  <p>Any solution on how to by-pass the validator only in that particular case?</p>