With this code I check whether a username is valid or not:
public class UniqueUsernameAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
IRepository<User> userRepository = new EFRepository<User>();
User user = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals((string) value));
return user == null;
}
}
This works fine when adding new users. But when editing users, one existing one will already be present in the database and so this code doesn’t work anymore (as I check if there are 0 entries, while 1 will exist already). Is there any way to add an extra parameter or something?
Thanks
You might try what this CodeProject article suggests: http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC3
Overriding the other IsValid would give you the options to include additional data including whether you are really looking for a new – non-dupliated user, or whether you are looking at an existing user.