I use CsvHelper.Configuration.ClassMap to read csv file and faced with data validation.
I found Validate option and wrote a simple code:
Map(m => m.Field).Name("myField").Validate(row => row.Contains('='));
But I don't understand an output and confused a bit with possible options.
So, my questions are:
If it returns true - will I receive string? Or boolean true? I want to add the value to DB after that..
If it returns false - what I receive? And, anyway, the value will not be added to DB?
Any ideas how to add simple validation? Usual code, without validation:
Map(m => m.Field).Name("myField");
Thank you in advance!
CodePudding user response:
You would write it this way using CsvHelper 27.1.1
Map(m => m.Field).Name("myField").Validate(x => x.Field.Contains('='));
In 15.0.3 you would not use Field
Map(m => m.Field).Name("myField").Validate(x => x.Contains("="));
The Validate function has the following signature :
public virtual MemberMap<TClass, TMember> Validate(Validate validateExpression);
The Validate Type is a delegate which is declared this way :
public delegate bool Validate(ValidateArgs args);
ValidateArgs has the property Field which i use in my code sample.
It will throw a FieldValidationException if the condition is false during the conversion.
You could catch this exception and add some logic.
- if true the conversion will work as expected you field will be mapped.
- A FieldValidationException will be thrown.
- See code above.