I am trying to implement a custom validation using "FluentValidation" into a WebApi project.
So, in my action method(POST) from Controller, I use the base class (Person) as parameter:
[Route("persons/compute")] public HttpResponseMessage Compute(Person person) { ... }
From nuget I have installed "FluentValidation and FluentValidation.WebApi" packages.
I have the follwing code:
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CNP { get; set; } //unique identifier
}
[Serializable]
[Validator(typeof(StudentValidator))]
public class Student : Person
{
public string CollegeName { get; set; }
}
Validator classes are:
public abstract class PersonValidator<T>: AbstractValidator<T> where T : Person
{
protected abstract PersonClassType PersonClassType { get; }
public PersonValidator()
{
Custom(p => {
if (string.IsNullOrEmpty(p.CNP))
{
return new ValidationFailure("Insured.UniqueIdentifier", "CNP/CUI obligatoriu!");
}
else
{
decimal cnp;
bool isCNP = (p.CNP.Length == 13 && decimal.TryParse(p.CNP, out cnp));
if (!isCNP)
{
return new ValidationFailure("Insured.UniqueIdentifier", "CNP invalid!");
}
}
return null;
});
}
}
The Validator for derived class is:
public class StudentValidator : PersonValidator<Student>
{
public StudentValidator ()
{
Custom(p => {
if (string.IsNullOrEmpty(p.CollegeName))
{
return new ValidationFailure("ekfjekfj", "College Name mandatory!");
}
return null;
});
}
protected override PersonClassType PersonClassType
{
get
{
return PersonClassType.Student;
}
}
}
[DataContract]
public enum PersonClassType
{
None = int.MinValue,
Student = 1,
Employee = 2
}
In Global.asax.cs, in Application_Start(), I added:
FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration);
What I need?: In action method, in controller, using the parameter of type base class(Person) to make the validation for children/derived(ex:Student, Employee, etc) classess which are received from body (POST). So, it need to know to switch to the right validator. I suppose that this issue could be resolved using "Factory" or "DepencyInjection", but I do not know how. I hope make myself clear. My appollogize, but my English it's not perfect.
I would appreciate an explicit solution because I have tried to implement with Factory but I did not managed. I could send the zip file with my code, if it is needed. Thanks a lot in advance!