SetValidator for complex properties not working
I have the following validation class for "Expense" entity:
public class ExpenseBaseValidator : AbstractValidator<Expense>
{
public ExpenseBaseValidator()
{
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.BusinessID).NotEqual(0).WithMessage("BusinessID is
required.");
RuleFor(x =>
x.ExpenseTypeID).NotEqual(0).WithMessage("ExpenseTypeID is
required.");
RuleFor(x => x.CreatedDate).NotNull();
RuleFor(x => x.Transaction).SetValidator(new TransactionValidator());
}
}
Then I have validation class for Transaction which is a complex property
in Expense class above:
public class TransactionBaseValidator : AbstractValidator<Transaction>
{
public TransactionBaseValidator()
{
RuleFor(x =>
x.BankAccountID).NotEqual(0).WithMessage("BankAccountID is
required.");
RuleFor(x => x.EmployeeID).NotEqual(0).WithMessage("EmployeeID is
required.");
RuleFor(x => x.TransactionDate).NotNull();
RuleFor(x => x.IsWithdrawal).NotNull();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.PaymentMethod).NotEmpty();
RuleFor(x => x.PaymentMethod).Length(0,
50).WithMessage("PaymentMethod can not exceed 50 characters");
}
}
Now these are base classes and I call the validator using the following
child classes respectively:
public class ExpenseValidator : ExpenseBaseValidator
{
public ExpenseValidator()
: base()
{
RuleFor(x => x.Transaction)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("An account transaction is required when the
amount is paid.");
RuleFor(x => x.DatePaid)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("Please enter the date when the expense was paid.");
}
}
And Transaction child class:
public class TransactionValidator : TransactionBaseValidator
{
public TransactionValidator() : base()
{
}
}
And these can have extra rules for validation and the base rules are
called using the base() constructor.
And I validate the Expense object using this:
var validator = new ExpenseValidator();
var results = validator.Validate(oExpense);
Now this doesn't return the validation for the complex property
transaction which I am using in the following way:
oExpense.Transaction = new Transaction();
oExpense.Transaction.Amount = oExpense.Amount;
oExpense.Transaction.BankAccountID = ddlAccounts.SelectedItem.Value.ToInt();
oExpense.Transaction.TransactionDate = oExpense.DatePaid.Value;
oExpense.Transaction.IsWithdrawal = true;
oExpense.Transaction.Description = oExpense.Description;
oExpense.Transaction.IsDeleted = false;
// I dont set the below and it should give me validation error:
// oExpense.Transaction.EmployeeID = 10;
I don't set the EmployeeID and it should give me validation error when I
call validator for expense object as it has SetValidator() for the
Transaction property and the Transaction is also not null as I already set
new Transaction().
Any idea?
No comments:
Post a Comment