samedi 1 août 2015

How to validate an array of EnumDataType using Data Annotations with C# from a unit test?

In ColorSettings model shown below, I'm able to validate property MyColor with EnumDataType to make sure that only the value defined in ColorsEnum can be entered as shown below. This works fine for a single string value of type ColorsEnum.

[Test]
public void ColorSettingsModel_MyColorEnum_Invalid()
{
  var sut = GetColorSettingsModel();
  sut.MyColor = "wrong color value";

  var context = new ValidationContext(sut, null, null);
  var validationResults = new List<ValidationResult>();
  var isModelStateValid = Validator.TryValidateObject(sut, context, validationResults, true);

  Assert.AreEqual(1, validationResults.Count);
  Assert.IsTrue(validationResults.Any(x => x.ErrorMessage == "MyColorEnum"));
}

How can I validate the field SelectedColors using a similar method that contains an array of type ColorsEnum? Is there a way to apply EnumDataType attribute to an array of type ColorsEnum?

public enum ColorsEnum
{
  red,
  blue,
  green
}

public class ColorSettings
{
  [Required(ErrorMessage = "MyColorRequired")]
  [EnumDataType(typeof(ColorsEnum), ErrorMessage = "MyColorEnum")]
  public string MyColor { get; set; }

  [Required(ErrorMessage = "SelectedColorsRequired")]
  // How to validate an array of EnumDataType ?
  public string[] SelectedColors { get; set; }

}

Aucun commentaire:

Enregistrer un commentaire