Skip to content

Add support for fields validation #56

Description

@ArtemkaKun

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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions