简体   繁体   中英

ASP MVC 5 Custom Validation Attribute to Compare Two Properties?

I have the following custom validation attribute to check if two properties are not the same but its applied to the entire model:

[AttributeUsage(AttributeTargets.Class)]
public class ValidateUser : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        UserViewModel user = value as UserViewModel;
        if(user.UserId == user.ManagerId)
        {
            ErrorMessage = "The user and manager cannot be the same";
            return false;
        }
        return true;

    }
}

[ValidateUser]
public class UserViewModel
{
   [DisplayName("Request By")]
   public string UserId { get; set; }

   [DisplayName("Assign To")]
   public string ManagerId { get; set; }
}

How can I create a validation attribute so that instead having to decoarate the entire view model I can decorate the properties that need validating so that the error message appears close to the field being validated. something like below:

   [DisplayName("Request By")]
   [ValidateUser]
   public string UserId { get; set; }

   [DisplayName("Assign To")]
   [ValidateUser]
   public string ManagerId { get; set; }

There is another possible way to validate Properties values is to use Remote attribute

In your Model class

 [DisplayName("Request By")]
 public string UserId { get; set; }


 [DisplayName("Assign To")]
 [Remote("Validate","Home", HttpMethod="Post", AdditionalFields="UserId", ErrorMessage = "Should not be same")]
       public string ManagerId { get; set; }

In your controller

[HttpPost]
public ActionResult Validate(string ManagerId , string UserId )
{
  // put some validation involving ManagerId and UserId here
  return Json(true);
}

Working Demo is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM