Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from christopherbauer/AtLeastOneAttribute.cs
Created September 25, 2017 01:54
Show Gist options
  • Save LSTANCZYK/b712f96b10a8bba3bf75239f4f05060d to your computer and use it in GitHub Desktop.
Save LSTANCZYK/b712f96b10a8bba3bf75239f4f05060d to your computer and use it in GitHub Desktop.
AtLeastOne Attribute and Validator Implementation for MVC 3+ (Note: only validates client-side)
[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;
}
}
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);
}
}
}
(function () {
'use strict';
$.validator.addMethod("atleastone", function(value, element, params) {
return $("[data-val-atleastone-groupname=" + params + "]:checked").length > 0;
});
$.validator.unobtrusive.adapters.add("atleastone", ["groupname"], function(options) {
options.rules["atleastone"] = options.params.groupname;
options.messages["atleastone"] = options.message;
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment