UI-O-Matic and using data annotations for validation

UI-O-Matic provides an simply way to validate your model by implementing the interface IUIOMatic and the member Validate() there you simply return a list of exceptions you wish to display to your editor, so you have full control over the validation logic… (as in the example shown here where it checks wether a value for the FirstName prop and LastName prop have been provider)

But something I have been toying with is the idea to use a .net standard instead which are data annotations. So you can simply decorate your properties with those (like [Required])

And luckily .net provides a way to manually validate those so we can actually use them allready, you’ll just have to write the validation code in the validate method and this end up with a mode like this

1 [UIOMatic("PollAnswers", "icon-poll", "icon-poll", RenderType = UIOMatic.Enums.UIOMaticRenderType.List)] 2 [TableName("PollAnswers")] 3 public class PollAnswer : IUIOMaticModel 4 { 5 [UIOMaticIgnoreField] 6 [PrimaryKeyColumn(AutoIncrement = true)] 7 public int Id { get; set; } 8 9 [Required] 10 public string Answer { get; set; } 11 12 [Required] 13 [StringLength(6, MinimumLength = 3)] 14 [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed in the Poll Identifier field")] 15 public string PollIdentifier { get; set; } 16 17 public IEnumerable<Exception> Validate() 18 { 19 var context = new ValidationContext(this, serviceProvider: null, items: null); 20 var results = new List<ValidationResult>(); 21 22 Validator.TryValidateObject(this, context, results,true); 23 24 return results.Select(r => new Exception(r.ErrorMessage)); 25 } 26 }

Leave a Reply