An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Consider using data annotations using a custom rule. Below I show validating a single entity, to validate a list, simple loop through the list and if validating on the fly the code allows var isValid = new ValidKeyAttribute().IsValid(value); where value is the number to validate.
/// <summary>
/// Custom rule for third digit
/// </summary>
public class ValidKeyAttribute : ValidationAttribute
{
public override bool IsValid(object sender)
{
string value = Convert.ToString(sender);
if (value.Length < 9)
{
return false;
}
return value[2] == '0' || value[2] == '3';
}
}
Using the following model to validate (below)
public class Athlete
{
[ValidKey]
[Required(ErrorMessage = "{0} is required")]
public int Id { get; set; }
[Required(ErrorMessage = "{0} is required")]
[MaxLength(15)]
public string FirstName { get; set; }
[Required(ErrorMessage = "{0} is required")]
[MaxLength(20)]
public string LastName { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
Unit test
[TestClass]
public partial class ValidKeyTests : TestBase
{
[TestMethod]
[TestTraits(Trait.Annotations)]
public void ValidKeyTest()
{
// arrange
int value = 123456789;
Athlete athlete = new () { Id = value, FirstName = "Jim", LastName = "Adams" };
// act
EntityValidationResult result = Model.Validate(athlete);
// assert
Check.That(result.IsValid).IsTrue();
}
[TestMethod]
[TestTraits(Trait.Annotations)]
public void NotValidBadIdKeyTest()
{
// arrange
int value = 126456789;
Athlete athlete = new() { Id = value, FirstName = "Jim", LastName = "Adams" };
// act
EntityValidationResult result = Model.Validate(athlete);
// assert
Check.That(result.IsValid).IsFalse();
}
[TestMethod]
[TestTraits(Trait.Annotations)]
public void NotValidNoIdKeyTest()
{
// arrange
Athlete athlete = new() { FirstName = "Jim", LastName = "Adams" };
// act
EntityValidationResult result = Model.Validate(athlete);
// assert
Check.That(result.IsValid).IsFalse();
}
}
And we can shortcut the above with var isValid = new ValidKeyAttribute().IsValid(value);
All source, C# 9, .NET Core code is in the following repository.