Add support for fields validation
Hi. I'm moving my model from class with properties to read-only struct, and I also want to save the same validations as I have previously.
Unfortunately, the Validator doesn't iterate over fields of the struct and skips all validations.
It would be a call to have validation work for fields as it works for properties.
Example model code where Validator doesn't validate fields
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace SpawnMetricsStorage.Models.MetricRecordFiles;
[method: JsonConstructor]
public readonly struct MetricRecord(string name, DateTime logTimeUtc, string commitGitHubUrl, string commitMessage, string value, string units)
{
[Required]
// TODO: Combine into one attribute since these are used in a few places
[MinLength(MetricRecordConstants.MinMetricNameLength)]
[MaxLength(MetricRecordConstants.MaxMetricNameLength)]
[JsonInclude]
public readonly string Name = name;
[Required]
[JsonInclude]
public readonly DateTime LogTimeUtc = logTimeUtc;
[Required]
[MinLength(MetricRecordConstants.MinCommitGitHubUrlLength, ErrorMessage = MetricRecordConstants.CommitGitHubUrlShorterErrorMessage)]
[MaxLength(MetricRecordConstants.MaxCommitGitHubUrlLength)]
[Url]
[RegularExpression(@"https:\/\/github\.com\/[^\/]+\/[^\/]+\/commit\/[\da-fA-F]{8}", ErrorMessage = "Invalid GitHub commit URL")]
[JsonInclude]
public readonly string CommitGitHubUrl = commitGitHubUrl;
[Required]
[MinLength(MetricRecordConstants.MinStringLength)]
[MaxLength(MetricRecordConstants.MaxCommitMessageLength)]
[JsonInclude]
public readonly string CommitMessage = commitMessage;
[Required]
[MinLength(MetricRecordConstants.MinStringLength)]
[JsonInclude]
public readonly string Value = value;
[Required]
[MinLength(MetricRecordConstants.MinStringLength)]
[MaxLength(MetricRecordConstants.MaxUnitsLength)]
[JsonInclude]
public readonly string Units = units;
}
Thanks for the request. This should be fairly straightforward to add, but I need to decide whether it should be behind a flag so as to not change behavior between versions, as that could very easily break folks. That said, folks can always skip members they don't want validated so perhaps best to keep consumption simple. I'll look at this for the 0.10.0 release.