CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Optional() is not working in my map

Open mnr9917 opened this issue 3 years ago • 2 comments

I have a map where I have 5 fields that are optional, but needs to be validated is they are not empty.

Map(m => m.mail1).Name("mail1").Optional().Validate(x => Regex.IsMatch(x.Field, @"regex...", RegexOptions.IgnoreCase));
Map(m => m.mail2).Name("mail2").Validate(x => Regex.IsMatch(x.Field, @"regex...", RegexOptions.IgnoreCase)).Optional();

I have tried these ways, but it stills returns a FieldValidationException. Is there a way where I can validate only if the field is not empty?

mnr9917 avatar Feb 24 '22 19:02 mnr9917

What do you mean by empty? Optional ignores the member if the field doesn't exist in the CSV. Validate isn't called if the field doesn't exist.

If you mean the field is null or an empty string, you'll have to handle that in your Validate method.

Map(m => m.mail1).Validate(x => string.IsNullOrEmpty(x.Field) || Regex.IsMatch(x.Field, @"regex...", RegexOptions.IgnoreCase));

JoshClose avatar Feb 24 '22 22:02 JoshClose

I have a model where I have these 5 fields public string mail1 { get; set; } public string mail2 { get; set; } public string mail3 { get; set; } public string mail4 { get; set; } public string mail5 { get; set; } But in the csv file, the columns can be empty strings, so, if the mail1 is null or empty string it should be skipped, and not return a FieldValidationException, but if mail1 contains a string, then it should do the validation. And that is the case for the five mails

mnr9917 avatar Feb 25 '22 16:02 mnr9917