Dealing with properties where null is valid #1120
-
I'm still learning the library, but I get stuck on things. In my case I have a DTO class with this property:
For this property, a null is perfectly valid; the date is not required. However, I still need to parse/validate the string to be sure it's a proper
The Parser works just fine for a valid date; it returns a properly parsed
I was hoping that a I also tried changing the
Any advice on how to validate a |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I'm not sure why do you still need to return nullable Anyway, IMHO the clearest solution is something like this: public static Validation<Error, DateTime> ParseNullableDateTime(string? dateTime)
=> Prelude.Optional(dateTime)
.Bind(Prelude.parseDateTime)
.ToValidation(Error.New($"{dateTime} is not a valid Date")) This signature is kind of strange: Validation<Error, DateTime?> Forget about null when you have already valid |
Beta Was this translation helpful? Give feedback.
-
I think you have it almost right with your last example. The Rather than propagating the nullable type, consider going all-in on using the alternate value monads. Changing the return type from public static Validation<Error, Option<DateTime>> ParseNullableDateTime(Option<string> value) =>
value.Match(
Some: d => DateTime.TryParse(d, out var date)
? Success<Error, Option<DateTime>>(date)
: Fail<Error, Option<DateTime>>(Error.New($"{d} is not a valid Date")),
None: () => Success<Error, Option<DateTime>>(None)); And if you do ever really need a nullable DateTime, you can still |
Beta Was this translation helpful? Give feedback.
I think you have it almost right with your last example. The
Value is null
exception you are getting is because LanguageExt forbids nulls unless explicitly allowed (using the____Unsafe
functions). In this case, theValidation
type does not have any overloads for accepting nulls.Rather than propagating the nullable type, consider going all-in on using the alternate value monads. Changing the return type from
Validation<Error, DateTime?>
toValidation<Error, Option<DateTime>>
provides the same information but with better safety. Now instead of aSuccess
case with a null value, we give itNone
.