I had written RegularExpression Attribute for some properties in my Object class. And while using CsvHelper, it seems like it is not validation to that. Could any one help here.
sample code
[JsonProperty("id")]
public int Id { get; set; }
[RegularExpression(@"^.*(\w+\s)*(\w+[\.\s])*\w*$", ErrorMessage = "Only Alpha Numerical , dot, underscore, space are allowed")]
[JsonProperty("Name")]
public string Name{ get; set; }
When I try to use with
csvReader.GetRecords<MyClass>().ToList();
it doesn't automatically make validation.
CsvHelper only recognizes the CsvHelper attributes. You could use the Validate method in a ClassMap
but it only gives a very basic exception, which isn't very helpful. I think your best bet is going to be to check the Name
property while manually reading the records.
void Main()
{
var _regex = new Regex(@"^[a-zA-Z0-9._ ]*$");
using (var reader = new StringReader("Id,Name\n1,Frank\n2,Jorda*n"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Read();
csv.ReadHeader();
var records = new List<Foo>();
while(csv.Read())
{
var record = csv.GetRecord<Foo>();
if (!_regex.IsMatch(record.Name))
{
throw new Exception($"Row: {csv.Context.Parser.Row}, Name: {record.Name}, Exception: Only Alpha Numerical, dot, underscore, space are allowed");
}
records.Add(record);
}
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}