I have user created page and obviously I don't want my users to have same usernames so I created my validation for that, however I have problem editing users now. When I try to edit user it won't allow me to do it since it says username already taken. But I don't even want to edit the username, just password or something.
Edit: I did made mistake by calling ValidateModel()
, now I fixed that but still run into problems.
Validator
public class UniqueUsername : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return true; // In Edit view you can't edit username so it's null
FinanceDataContext _db = new FinanceDataContext();
var user = _db.Users.ToList().Where(x => x.Username.ToLower() == value.ToString().ToLower()).SingleOrDefault();
if (user == null) return true;
return false;
}
}
Model
public class User
{
public int ID { get; set; }
// When I remove UniqueUsername and Remote validators everything works just fine
[Required]
[UniqueUsername(ErrorMessage = "Username is already taken")]
[Remote("CheckUsername", "User", null, ErrorMessage = "Username is allready taken", HttpMethod = "POST")]
public string Username { get; set; }
[Required]
public string Password { get; set;}
}
Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(User u)
{
// Get user we want to edit
var user = _db.Users.Where(x => x.ID == u.ID).SingleOrDefault();
if (user == null) return HttpNotFound();
// Set new fields manually
if (!string.IsNullOrEmpty(u.Password)) user.Password = Infrastructure.Encryption.SHA256(u.Password);
ModelState.Remove("Username"); // this doesen't seem to do much...
_db.SaveChanges(); // validation error here
return Content(Infrastructure.Helper.SerializeObject(u));
}
Error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I know why it throws me error. Because he checks if Username is already taken, and of course it's taken but I want to validate if username is taken only on CREATE, not on EDIT (since you can't change your username)