如何在Fluent Model Validator中访问属性值?下面是 ModelA的验证器类。 ModelA有一个名为isValid的bool属性。 如何在此类中访问布尔值?。
public class ModelAValidator :
AbstractValidator<ModelA>
{
public ModelAValidator()
{
var regexPatterns = new RegExPatterns();
RuleFor(x => x.FirstName)
.RequiredForBeneficiaryWhen(x => x.IsBeneficiaryValid)
.WithLocalizedMessage(ResourceAreas.Messages.Message_PersonalDetails_1001_firstname)
RuleFor(x => x.FirstLastName).
RequiredForBeneficiaryWhen(x => x.IsBeneficiaryValid)
.WithLocalizedMessage(ResourceAreas.Messages.Message_PersonalDetails_1001_firstname)
}
}
ExtensionMethod -
public static IRuleBuilderOptions<T, TProperty>
RequiredForBeneficiaryWhen<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, bool>> conditionalProperty)
{
var validationrule = new UnobtrusiveValidationRule()
{
ValidationType = "mvfbenefreq"
};
return
ruleBuilder.SetValidator(new
BeneficiaryRequiredValidation<T>(conditionalProperty,
false, validationrule));
}
属性验证器 -
public class BeneficiaryRequiredValidation<T> : PropertyValidator, IClientValidatable
{
public object CompareTo { get; private set; }
public UnobtrusiveValidationRule ClientValidationRule { get; set; }
private readonly Expression<Func<T, bool>> _conditonalExpression;
private readonly bool _conditionalValue;
public BeneficiaryRequiredValidation(Expression<Func<T, bool>> compareExpression, bool conditionalValue , UnobtrusiveValidationRule clientvalidationrule)
: base(FluentValidation.Resources.Messages.lessthan_error)
{
ClientValidationRule = clientvalidationrule;
_conditonalExpression = compareExpression;
_conditionalValue = conditionalValue;
}
protected override bool IsValid(PropertyValidatorContext context)
{
return true;
}
[ExcludeFromCodeCoverage]
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var formatter = new MessageFormatter().AppendPropertyName(metadata.PropertyName);
var message = formatter.BuildMessage(ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule
{
ErrorMessage = message,
ValidationType = ClientValidationRule.ValidationType
};
if (ClientValidationRule.Parameterlist != null)
{
foreach (var entry in ClientValidationRule.Parameterlist)
{
rule.ValidationParameters.Add(entry.Key, entry.Value);
}
}
yield return rule;
}
}
谢谢
答案 0 :(得分:0)
假设RequiredForBeneficiaryWhen
看起来像这样:
private bool RequiredForBeneficiaryWhen(string requiredStr, bool isValid)
{
//Require value specified if isValid is true
if (isValid)
return !string.IsNullOrEmpty(requiredStr);
//It isn't valid
return false;
}
然后你可以使用Must
重写规则:
RuleFor(x => x.FirstName)
.Must((model, firstName) => RequiredForBeneficiaryWhen(firstName, model.IsBeneficiaryValid))
.WithLocalizedMessage(ResourceAreas.Messages.Message_PersonalDetails_1001_firstname)