Add validation msg to Validate Func
Closes #1198
- Add a way to associate an exception message with Validate lambda.
- Add Unit test to above functionality.
wondering if it is okay to use FluentAssertion lib
Does Assert.ThrowsException not work in this case?
I think instead of a string message, it should probably be a Func<string, string> so the user can use the field that failed validation in the message if they want. I was thinking if the whole row would be valuable, but that data should be passed along as part of the exception that is thrown.
Something like this:
public virtual new MemberMap<TClass, TMember> Validate(Func<string, bool> validateExpression, Func<string, string> validateMessageExpression)
{
Data.ValidateExpression = (Expression<Func<string, bool>>)(field => validateExpression(field));
Data.ValidateMessageExpression = (Expression<Func<string, string>>)(field => validateMessageExpression(field));
return this;
}
Does
Assert.ThroeExceptionnot work in this case?
Assert.ThrowException doesn't allow for thrown message inspection so it can't be asserted and that's why I used FluentAssertion I could do it with an ExtensionMethod but Ifind the lib is a more natural approach.
I don't see a use case for func<string,string>
The field is already a member of The exception itself and can be read/used. What would be a use case ? Can you give me an example?
I would think people would naturally want to put it in their message.
$"Validation failed: Field '{field}' cannot contain spaces."
I would think people would naturally want to put it in their message.
$"Validation failed: Field '{field}' cannot contain spaces."
I'll see what I can do, I'm trying now to figure out how to invoke that expression. But what would the expression achieve? like from your example the expression will execute and if evaluated not to true be passed along to the exception constructor like I did originally or something different?
@JoshClose
I did the change. Could you take a look?
Thanks.
bump?? @JoshClose
This could make life much easier for me. What's the status of this @micheleissa and @JoshClose?
It'll still be at least a few weeks. I'm very swamped with work.
Hi all, this feature would be super useful for me for too. Do you have any updates @JoshClose? I know a good software engineer is a busy software engineer.
I'm looking for a resolution to this as well. Any word?
As a work around, you can throw your own Exception type with its own message instead of returning false in your validation. That will get cauight and wrapped by CsvHelper in a CsvHelperException which will contain the context and the inner exception will be your exception, Catch the CsfHelperException and use the inner exception to get your message.