Sorry, If this question seems too broad, but I'm a little unsure how I should do this task.
I have some objects:
public class A
{
public B b {get;set;}
public C[] cList {get;set;}
}
public class B
{
public string val1 {get;set;}
}
public class C
{
public string val2 {get;set;}
}
And a set of validators:
public class AValidator : IValidator<A>
{
IEnumerable<ValidationError> Validate(A obj){...}
}
public class BValidator : IValidator<B>
{
IEnumerable<ValidationError> Validate(B obj){...}
}
public class CValidator : IValidator<C>
{
IEnumerable<ValidationError> Validate(C obj){...}
}
Error looks like this:
public class ValidationError
{
public int Code {get;set;}
public string Message {get;set;}
}
I perform validation like this:
_validator.Validate(new A()).ThrowIfInvalid();
But here is the problem, how to reference invalid property and Serialize/Deserialize this reference to use it on client?
For example, if new A().c[2].val2
is invalid, I should be able to obtain this path on server and use it on client for my view (obtain PropertyInfo, and object).
Is there some extensions/libraries in C# which provide serializable references for properties? For example, like XPath in XML.
Extend class ValidationError
with PropertyPath
property and prepend it on each parent validator
public class AValidator : IValidator<A>
{
IEnumerable<ValidationError> Validate(A obj)
{
if(obj.b == null)
yield return new ValidationError {Message = "b is null", PropertyPath = "a.b"};
else
{
var bresults = new BValidator().Validate(obj.b);
foreach(var result in bresults)
{
result.PropertyPath = "a.b." + result.PropertyPath;
yield return result;
}
}
...
var cresults = new BValidator().Validate(obj.c[i]);
foreach(var result in cresults)
{
result.PropertyPath = "a.c[i]." + result.PropertyPath;
yield return result;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.