I have the following model
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; }
}
the custom function MailNotExists is the following
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 => u.email == (string)value);
if (user == null)
return ValidationResult.Success;
else
return new ValidationResult("Mail already exists");
}
}
}
The model is used into the view to give the user the possibility to change his mail, trough
@Html.EditorForModel();
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 [MailNotExists] 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.
Any solution on how to by-pass the validator only in that particular case?