public class AtLeastOneAttributeTests
{
public class Test
{
}
[TestFixture]
public class when_getting_client_validation_rules
{
[Test]
public void then_should_return_validation_parameters_containing_key_value_pair_groupname_and_property_value_of_groupname()
{
// Arrange
var attribute = new AtLeastOneAttribute("Test");
// Act
var clientValidationAttributes = attribute.GetClientValidationRules(ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Test)), new Mock<ControllerContext>().Object);
// Assert
Assert.That(clientValidationAttributes,
Has.All.Matches<ModelClientValidationRule>(rule => rule.ValidationType == "atleastone")
.And.Matches<ModelClientValidationRule>(
rule =>
rule.ValidationParameters.Contains(new KeyValuePair<string, object>("groupname", "Test"))));
}
}
[TestFixture]
public class when_checking_is_valid
{
[Test]
public void then_should_return_true()
{
// Arrange
var attribute = new AtLeastOneAttribute("Test");
// Act
var result = attribute.IsValid(new Test());
// Assert
Assert.That(result,Is.True);
}
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AtLeastOneAttribute : ValidationAttribute, IClientValidatable
{
public string GroupName { get; private set; }
public AtLeastOneAttribute(string groupName)
{
GroupName = groupName;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = "At least one of Coupon or Upc or Promo is required.",
ValidationType = "atleastone",
ValidationParameters =
{
new KeyValuePair<string, object>("groupname", GroupName),
}
};
}
public override bool IsValid(object value)
{
return true;
}
}