내 속성 값을 내 모델 클래스의 다른 속성 값과 비교하려는 사용자 지정 유효성 검사 특성을 만들려고합니다. 내 모델 클래스에있는 예를 들어 :사용자 정의 유효성 검사 속성을 만드는 방법은 무엇입니까?
...
public string SourceCity { get; set; }
public string DestinationCity { get; set; }
내가 정의를 만들려면이처럼 사용하는 속성 :
[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity
어떻게 내가 거기받을 수 있나요?
public class CustomAttribute : ValidationAttribute
{
private readonly string _other;
public CustomAttribute(string other)
{
_other = other;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_other);
if (property == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _other)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
// at this stage you have "value" and "otherValue" pointing
// to the value of the property on which this attribute
// is applied and the value of the other property respectively
// => you could do some checks
if (!object.Equals(value, otherValue))
{
// here we are verifying whether the 2 values are equal
// but you could do any custom validation you like
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx – Joe
@Joe, ASP.NET MVC 2 용이며 더 이상 MVC 3에 적용되지 않습니다. 또한이 블로그 게시물은 OP가 여기에서 달성하려고하는 바리케이터에서 종속 속성 값을 검색하는 방법을 설명하지 않습니다. –