ASP MVC 5自定义验证属性比较两个属性?

时间:2016-08-06 17:10:57

标签: c# asp.net-mvc validation customvalidator validationattribute

我有以下自定义验证属性来检查两个属性是否不相同但是它应用于整个模型:

[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; }
}

如何创建验证属性,以便必须装饰整个视图模型,我可以修饰需要验证的属性,以便错误消息显示在要验证的字段附近。如下所示:

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

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

1 个答案:

答案 0 :(得分:-1)

另一种可能的方法来验证属性值是使用Remote属性

在您的模型类中

 [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; }

在你的控制器中

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

Working Demo is here