using System.ComponentModel.DataAnnotations; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.OpenApi.Models; namespace NejCommon.Validation; public class RegexAttribute : NejValidationAttribute { public override string ExampleJson { get; } public string Pattern { get; } public RegexAttribute(string pattern, string example, string errorMsg = null) { Pattern = pattern; ExampleJson = JsonSerializer.Serialize(example); ErrorMessage = errorMsg ?? $"Invalid format (must match {pattern})"; } protected override ValidationResult IsValid(object value, ValidationContext ctx) { if (value is null) return ValidationResult.Success!; var str = value as string; if (string.IsNullOrWhiteSpace(str) || !Regex.IsMatch(str, Pattern)) return new ValidationResult(ErrorMessage); return ValidationResult.Success!; } public override void ApplySchema(OpenApiSchema schema) { base.ApplySchema(schema); schema.Pattern = Pattern; } }