Optional() is not working in my map
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?
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));
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