Fluent Validation 규칙 빌더의 확장 기능을 작성하는 동안보다 복잡한 유효성 검사를 한 다음 클라이언트 유효성 검사를 사용하여 연결하는 아이디어가 떠 올랐습니다. 다른 속성을 기반으로 한 속성을 확인하는 확장 프로그램을 성공적으로 만들었습니다.복잡한 유효성 검사 확장
확장 방법으로 유창하게 규칙을 추가 허용하는 MyRuleBuilder 클래스 https://fluentvalidation.codeplex.com/wikipage?title=Custom&referringTitle=Documentation
public static IRuleBuilderOptions<T, TProperty> Required<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Action<MyRuleBuilder<T>> configurator)
{
MyRuleBuilder<T> builder = new MyRuleBuilder<T>();
configurator(builder);
return ruleBuilder.SetValidator(new MyValidator<T>(builder));
}
에 : 내가 고민하고하는 것은 여러 필드에 대한 유효성 검사입니다
public class MyRuleBuilder<T>
{
public Dictionary<string, object> Rules = new Dictionary<string,object>();
public MyRuleBuilder<T> If(Expression<Func<T, object>> exp, object value)
{
Rules.Add(exp.GetMember().Name, value);
return this;
}
}
다음 뷰 모델과 뷰 모델 유효성 검사기 규칙은 다음과 같습니다.
public class TestViewModel
{
public bool DeviceReadAccess { get; set; }
public string DeviceReadWriteAccess { get; set; }
public int DeviceEncrypted { get ; set; }
}
RuleFor(x => x.HasAgreedToTerms)
.Required(builder => builder
.If(x => x.DeviceReadAccess, true)
.If(x => x.DeviceReadWriteAccess, "yes")
.If(x => x.DeviceEncrypted, 1));
문제 :
위의 작동하지만 괜찮아요 "If"기능입니다. 선택한 속성 유형의 값을 적용하지 않습니다. 예 :
RuleFor(x => x.HasAgreedToTerms)
.Required(builder => builder
.If(x => x.DeviceReadAccess, true) // I would like the value to be enforced to bool
.If(x => x.DeviceReadWriteAccess, "yes") // I would like the value to be enforced to string
// Ideally something like
// public MyRuleBuilder<T> If(Expression<Func<T, U>> exp, U value) but unfortunately U cannot be automatically inferred
는이 아키텍처를 가능 또는 내가 다른 접근 방식을 취해야합니까?
감사합니다.
이 경우 T는 TestViewModel 유형이고 U는 어떤 유형입니까? MyRuleBuilder이있는 필수 확장 함수에 작업 대리자가 있다는 것을 기억하십시오. 여기서 뭐라 구요? –
Zanuff
@Zanuff 맞아 ... 인터페이스에 또 다른 일반 매개 변수를 추가해야합니다 ... 매개 변수가 변경되어 Action'을 전달해야합니다. 그렇게 할 수 있는지 확실하지 않습니다. ... –
dburner
@ Zanuff 나는 제네릭 매개 변수를 메서드에 추가하지 않았다는 것을 깨달았습니다 .... 제 편집을 확인하십시오. – dburner