dotnet / dotNext

Next generation API for .NET
https://dotnet.github.io/dotNext/
MIT License
1.56k stars 119 forks source link

Using Optional<T> with data validation attributes #204

Closed Tiberriver256 closed 7 months ago

Tiberriver256 commented 7 months ago

Hello,

Is there any easy way to support making a class like this?

public class TestObject
{
    [StringLength(100)]
    public Optional<string?> Testing { get; set; }
}

and then expecting it to work with normal validation?

sakno commented 7 months ago

StringLengthAttribute is explicit about the type. It expects String, array, or collection type. TypeConverter doesn't help, the attribute doesn't use it for type conversion.

'System.InvalidCastException' in System.ComponentModel.Annotations.dll: 'The field of type DotNext.Optional`1[System.String] must be a string, array or ICollection type.'

I see no way in .NET library to override this behavior.

sakno commented 7 months ago

The only way is to derive StringLengthAttribute class and override bool IsValid (object? value); method. Let's call this OptionalStringLengthAttribute. If this approach works for you, I can prepare a few validation classes especially for Optional<T> data type.

Tiberriver256 commented 7 months ago

Ah thanks man! Yeah that sounds like a good way forward.

sakno commented 7 months ago

Please review the commit above. OptionalStringLengthAttribute and ValueRequiredAttribute classes are introduced. Counterparts of MinLengthAttribute and MaxLengthAttribute were not introduced because it makes no sense to use Optional<List<T>> data types in data models.

Tiberriver256 commented 7 months ago

Looks awesome man! Thank you!