[RESOLVED]Conditional Validation for [Remote] data annotation attribute?

Hi, have a property UserId in my entity class which has the [Remote] attribute to check if user id already exists while entering new record.

This works like a charm, however when I am in edit mode it still gives me the "User id already exists:" validation error.

FYI, I am using the same view for Add & Edit, I can create a separate view for edit to eliminate this problem but I would like to know is there a easy way to fix it?

Entity Class

[Key]
[Required]
[Display(Name="Username")]
[Remote("doesUserNameExist", "User", HttpMethod = "POST", ErrorMessage = "UserId already exists. Please enter a different user name.")]
public string UserId { get; set; }

Controller Action

 [HttpPost]
 public JsonResult doesUserNameExist(string UserId)
 {

    var user = repository.GetUser(UserId);

    return Json(user == null);
 }

Thanks & Regards
 

The doesUserNameExist(string UserId) method returns true if the UserId does NOT exist.  Is that the expected logic?

mgebhard

The doesUserNameExist(string UserId) method returns true if the UserId does NOT exist.  Is that the expected logic?

Hi, thanks for your reply.

Yes that is expected logic, do you think I should change it?

Thanks & Regards

Hi siteslayer,

For this issue, you could set the additional fields, which to use for check whether it has initial data.

For example:

[Remote("doesUserNameExist", "User", HttpMethod = "POST", ErrorMessage = "UserId already exists. Please enter a different user name.", AdditionalFields="InitUserName")]
@Html.Hidden("InitUserName", Model.Name)
[HttpPost]
 public JsonResult doesUserNameExist(string UserId,string InitUserName)
 {
    if(!(String.IsNullOrEmpty(InitUserName)&&String.IsNullOrWhiteSpace(InitUserName))
       {
         //TODO return false
       }
    //For else
    var user = repository.GetUser(UserId);

    return Json(user == null);
 }

Best Regards

Starain

Leave a Reply