Reputation: 147
I'm currently setting up a database using Entity Framework Code First, and I got the next field:
[Required]
public string Month { get; set; }
What I want to do, is to only allow certain inputs to be accepted in the field. For example, I want Month to only accept [01,02,03,04,05,06,07,08,09,10,11,12]. How should I approach this? I couldn't find any DataAnnotation to solve my problem.
Upvotes: 1
Views: 1459
Reputation: 14640
You can implement IValidatableObject
to validate Month
.
public class YourEntity : IValidatableObject
{
[Required]
public string Month { get; set; }
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
var months = Enumerable.Range(1, 12).Select(x => x.ToString("00"));
if (!months.Contains(Month))
{
yield return
new ValidationResult("Invalid month value.", new[] { "Month" });
}
}
}
More
Upvotes: 2