I would like to validate that a username is not already in use when adding or editing a user in my solution.
Here is what I do with the remote validation:
ViewModel:
[Required, Remote("UserNameAlreadyExists", "User", Error="Already exists!")]
public string UserName { get; set; }
Controller:
public ActionResult UserNameAlreadyExists(string userName)
{
var user = _requestServiceClient.GetUserFromUserName(userName);
return Json(user == null, JsonRequestBehavior.AllowGet);
}
It works pretty well for the creation. But It doesn’t work with edition because the username already exist for the edited user himself. Do you know what I mean?
A solution would be to check in DB based on UserName and UserID. So in the case of editing a user, we can check that the username does not exist yet (except the userid passed as parameter). Is it a good alternative? How to pass this userID in the Remote validation attribute?
Thanks.
If your users cannot change their username after creation then use a different view model for the editing where you just display the
UserNamewithout any validation.Otherwise you can use the AdditinalFields property to pass extra data to your validator:
You will also need to include the
Idproperty in yourformeg: