[英]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 验证属性值的另一种可能方法是使用Remote
属性
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.