I’m trying to write a custom validation class that validates that an email is not already is use. To do this, I have a method that counts the userprofiles that have the email address in question. Simple enough, but if the user is updating their profile, I need to exclude their profile from the count I mentioned about. So to do that, I have written the following method:
public static bool IsEmailUnique(string email, int userprofileId)
{
int count = -1;
using (var db = new TRDataContext())
{
count = (from u in db.Userprofiles
where u.email == email &&
(userprofileId == 0 || u.userprofile_id != userprofileId)
select u).Count();
}
return count == 0;
}
This works well in the custom validator class for new users as all I need to do is pass a 0 in for the userprofile_id.
public class EmailValidatorAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return false;
return Userprofile.IsEmailUnique(value.ToString(), 0);
}
}
and implemented like this
[DisplayName("Email Address")]
[Required(ErrorMessage = "Required")]
[RegularExpression(EmailRegex, ErrorMessage = "Invalid email address")]
[EmailValidator(ErrorMessage = "Already in use")]
public string email { get; set; }
However, I now need to pass into the EmailValidator the userprofile_id of that current user. I am having a difficult time figuring this one out.
Any help would be greatly appreciated.
Thanks!
I have had a similar issue. Firstly I implemented a ‘CurrentUser’ method in my user repository that looks a little something like this:
You can then use this to get the id from inside your validation attribute in a manner similar to the below: