我有下面的類FluentValidation呼叫規則集和通用規則
public class ValidProjectHeader : AbstractValidator<Projects.ProjectHeader>
{
public ValidProjectHeader()
{
RuleFor(x => x.LobId).Must(ValidateLOBIDExists);
RuleFor(x => x.CreatedByUserId).NotEmpty();
RuleFor(x => x.ProjectManagerId).NotEmpty();
RuleFor(x => x.ProjectName).NotEmpty();
RuleFor(x => x.SalesRepId).NotEmpty();
RuleFor(x => x.DeliveryDate).NotEmpty();
RuleFor(x => x.ProjectStatusId).NotEmpty();
RuleFor(x => x.DeptartmentId).NotEmpty();
RuleFor(x => x.CustomerId).NotEmpty();
RuleSet("Insert",() =>
{
RuleFor(x => x.ProjectLines).Must(ValidateProjectLines).SetCollectionValidator(new ValidProjectLine());
});
RuleSet("Update",() =>
{
RuleFor(x => x.ProjectLines).SetCollectionValidator(new ValidProjectLine());
});
}
和我所試圖做的是調用驗證與rulset但我也希望當我打電話回「常用」規則使用RuleSet進行驗證。
我有打電話驗證的代碼如下
public abstract class BaseValidator
{
private List<ValidationFailure> _errors;
public bool IsValid { get; protected set; }
public List<ValidationFailure> Errors
{
get { return _errors; }
protected set { _errors = value; }
}
public virtual bool CallValidation()
{
Errors = new List<ValidationFailure>();
ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute;
IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator;
FluentValidation.Results.ValidationResult result = validator.Validate(this);
IsValid = result.IsValid;
Errors = result.Errors.ToList();
return result.IsValid;
}
public virtual bool CallValidation(string ruleSet)
{
Errors = new List<ValidationFailure>();
ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute;
IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator;
FluentValidation.Results.ValidationResult result = validator.Validate(new FluentValidation.ValidationContext(this, new PropertyChain(), new RulesetValidatorSelector(ruleSet)));
IsValid = result.IsValid;
Errors = result.Errors.ToList();
return result.IsValid;
}
public BaseValidator()
{
Errors = new List<ValidationFailure>();
}
}
我可以調用該方法CallValidation
與成員ruleSet
,但他並沒有叫「共同」的規則也。
我知道我可以創建一個「Common」RuleSet來運行這些規則,但在這種情況下,我將不得不始終使用Common RuleSet調用驗證。
有沒有什麼辦法可以調用RuleSet並調用通用規則。
從2009年起,這個選項似乎並不存在於git源代碼中,這是由於文檔不正確導致我在這裏引起的。 – john
偉大的建議!在FluentValidation 6.2.1中,RuleSet參數大小寫是不同的:「ruleSet:」而不是「Ruleset:」。例如:validator.Validate(obj,ruleSet:「default,Insert」); –