I'm using the System.ComponentModel.DataAnnotations.CustomValidationAttribute to validate one of my POCO classes and when I try to unit test it, it's not even calling the validation method.
public class Foo
{
[Required]
public string SomethingRequired { get; set }
[CustomValidation(typeof(Foo), "ValidateBar")]
public int? Bar { get; set; }
public string Fark { get; set; }
public static ValidationResult ValidateBar(int? v, ValidationContext context) {
var foo = context.ObjectInstance as Foo;
if(!v.HasValue && String.IsNullOrWhiteSpace(foo.Fark)) {
return new ValidationResult("Either Bar or Fark must have something in them.");
}
return ValidationResult.Success;
}
}
but when I try to validate it:
var foo = new Foo {
SomethingRequired = "okay"
};
var validationContext = new ValidationContext(foo, null, null);
var validationResults = new List<ValidationResult>();
bool isvalid = Validator.TryValidateObject(foo, validationContext, validationResults);
Assert.IsFalse(isvalid); //FAIL!!! It's valid when it shouldn't be!
It never even steps into the custom validation method. What gives?
Try using the overload that takes a bool that specifies if all properties should be validated. Pass true for the last parameter.
public static bool TryValidateObject(
Object instance,
ValidationContext validationContext,
ICollection<ValidationResult> validationResults,
bool validateAllProperties
)
If you pass false or omit the validateAllProperties, only the RequiredAttribute will be checked.
Here is the MSDN documentation.
Related
So I have checked out this answer ASP:NET MVC 4 dynamic validation of a property depending of the current value of another property and it does not cover the issue I am having.
I am using server side validation. I have a requirement that...
A value is only required if another property is specified
Issue
MVC binds each property and calls each validator on that property as it binds them. If I am dependent on multiple properties being set when I check validationContext.ObjectInstance.[MY_DEPENDENT_PROPERTY] there is a possibility that those dependent properties have not been bound yet.
What I need is a validation attribute that validates after binding - if that even exists.
So here is a simple example to explain my situation (not intended to be executed as it will more than likely be fine since the issue has to do with binding order)
My model
public class Address
{
[Required]
public string ResidentialAddress { get; set; }
public bool PostalIsTheSameAsResidential { get; set; }
// will only be required if PostalIsTheSameAsResidential is false.
// see the static method below and RequiredIfAttribute
[RequiredIf(typeof(Address), nameof(PostalRequiredIfNotSameAsResidential)]
public string PostalAddress { get; set; }
public static bool PostalRequiredIfNotSameAsResidential(Address model)
{
return !model.PostalIsTheSameAsResidential;
}
}
My validator
Essentially what happens here is it calls the static method on the model to see whether it should validate.
public sealed class RequiredIfAttribute : RequiredAttribute
{
private readonly MethodInfo _validationMethod;
public override bool RequiresValidationContext => true;
public RequiredIfAttribute(Type type, string methodName)
{
this._validationMethod = type.GetMethod(methodName);
if (this._validationMethod == null)
{
throw new MethodAccessException($"The validation method '{methodName}' does not exist on type '{type}");
}
}
public override bool IsValid(object value)
{
throw new NotSupportedException();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult result = ValidationResult.Success;
var parameters = this._validationMethod.GetParameters();
var returnType = this._validationMethod.ReturnType;
if (returnType == typeof(bool) && parameters.Length == 1 && parameters[0].ParameterType == validationContext.ObjectType)
{
if ((bool)_validationMethod.Invoke(null, new object[] { validationContext.ObjectInstance }))
{
if (!base.IsValid(value))
{
string[] memberNames;
if (validationContext.MemberName == null)
{
memberNames = null;
}
else
{
memberNames = new string[1];
memberNames[0] = validationContext.MemberName;
}
result = new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName), memberNames);
}
}
return result;
}
var expectedFuncType = typeof(Func<,>).MakeGenericType(validationContext.ObjectType, typeof(bool));
throw new MethodAccessException($"The validation method '{this._validationMethod}' does not have the correct definition. Expected '{expectedFuncType}'");
}
}
So this issue that I was having was that I was inheriting from the RequiredAttribute. Internally MVC handles this attribute differently to everything else.
When the Model Binder is looping through the properties, it gets the RequiredAttributes and executes them at the same time...
// System.Web.Mvc.DefaultModelBinder.SetProperty
....
ModelValidator modelValidator = (from v in ModelValidatorProviders.Providers.GetValidators(modelMetadata, controllerContext)
where v.IsRequired
select v).FirstOrDefault<ModelValidator>();
if (modelValidator != null)
{
foreach (ModelValidationResult current in modelValidator.Validate(bindingContext.Model))
{
bindingContext.ModelState.AddModelError(key, current.Message);
}
}
....
That v.IsRequired actually resolves to a line that tests if the current attribute is a RequiredAttribute and will validate it there, in the current, incomplete model state.
By inheriting from ValidationAttribute it ran the validations after the model had been built and solved my issue.
Thanks to #StephenMuecke for prompting me with this.
I need to compare two properties in a class using .net data annotations. One of the two properties should be filled and the other should be blank. How can I override the behavior of the CompareAttribute ? If it is not possible, what's the alternative solution ?
This class works with one issue:
If Property A is set to something and property B already has a value, then property A becomes invalid as expected. Upon Blanking property B, property A should become valid but it won't until I try to modify property A so I trigger the validation again. Is there a way to connect the two together to trigger the validation on both one either one changes ?
class CustomAttribute : ValidationAttribute
{
private readonly string _other;
public CustomAttribute(string other)
{
_other = other;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_other);
if (property == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _other)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
if (!String.IsNullOrEmpty(value.ToString()) && !String.IsNullOrEmpty(otherValue.ToString()))
{
return new ValidationResult("Test");
}
return null;
}
}
For stuff like this I use ExpressiveAnnotations. It has a brilliant RequiredIf attribute:
[RequiredIf("B == null", ErrorMessage = "Either A or B should be filled")]
public string A { get; set; }
[RequiredIf("A == null", ErrorMessage = "Either A or B should be filled")]
public string B { get; set; }
You can extend the CompareAttribute with your own class:
public class CustomCompareAttribute: CompareAttribute {
public CustomCompareAttribute(string otherProperty) : base(otherProperty) {
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (OtherProperty == null && value == null) {
return new ValidationResult("Either A or B should be filled");
}
// more checks here ...
}
}
I'm having a bit of trouble getting my head around testing my custom validation attribute. As the method signature is protected when I invoke the IsValid method in my unit test, I can't pass in a Mock<ValidationContext> object, it's calling the base virtual bool IsValid(object value) instead.
ValidationAttribute
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (value != null)
{
if (otherPropertyValue == null)
{
return new ValidationResult(FormatErrorMessage(this.ErrorMessage));
}
}
return ValidationResult.Success;
}
Test
[Test]
public void Should_BeValid_WhenPropertyIsNullAndOtherPropertyIsNull()
{
var attribute = new OptionalIfAttribute("test");
var result = attribute.IsValid(null);
Assert.That(result, Is.True);
}
If I'm unable to pass in a mocked validation context, then how can I test this class properly?
You can use the Validator class to perform the validation manually without having to mock anything. There is a brief article on it here. I would probably do something like
[Test]
public void Should_BeValid_WhenPropertyIsNullAndOtherPropertyIsNull()
{
var target = new ValidationTarget();
var context = new ValidationContext(target);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(target, context, results, true);
Assert.That(isValid, Is.True);
}
private class ValidationTarget
{
public string X { get; set; }
[OptionalIf(nameof(X))]
public string OptionalIfX { get; set; }
}
You could optionally make assertions on results.
This is about Data Annotations in C#.
I have a class called MyClass. There I will be having two properties.
class MyClass
{
private string _propName;
public string PropName
{
get {return _propName;}
set {_propName=value;}
}
private string _propVal;
public string PropVal
{
get {return _propVal;}
set {_propVal=value;}
}
}
I have a MS SQl table which contains data for propName and relevant propValue.
I need to have validations using DataAnnotations. Each and every _propName need to have different validations.
My question is : How do I add different validations/data annotations to the class structure I have mentioned above ? I was wondering whether or not there is some way to specify if-else conditions in Data Annotations ?
if "this propertyname"
validation 1
else if "that property name"
validation 1
Can someone help ?
You should be able to something like this:
public class MyValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
switch (validationContext.MemberName)
{
//some logic
}
}
}
The problem is with ValidationAttribute your only going to get the value of the one property, not the combination of the properties, what you can do is combine the PropName and PropVal in a tuple, and then validate that.
This little test app shows a method of achieving what you want.
public class MyClass {
[MyValidation]
public Tuple<string, string> PropValue { get; set; }
public List<ValidationResult> TestValidation() {
var validationContext = new ValidationContext(this, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, results, validateAllProperties: true);
return results;
}
}
public class MyValidationAttribute : ValidationAttribute {
public override bool IsValid(object value) {
var propValue = value as Tuple<string, string>;
if (propValue.Item1 == "Item") {
var setPropValue = propValue.Item2;
//Do you validation
}
return true;
}
}
class Program {
static void Main(string[] args) {
MyClass instance = new MyClass();
instance.PropValue = new Tuple<string, string>("Item", "Value");
var result = instance.TestValidation();
}
}
I am trying to create my own validation attribute IsUnique that checks existing values for given property. I understand IsValid() must be overridden so that custom validation attribute can work. So far I have seen examples with validate attributes that take a string parameters which is then compared with hard coded values inside IsValid() method.
I need IsValid() method to get access to a property and its value to further compare it with values in the database.
This is what I have done so far:
public class IsUnique : ValidationAttribute
{
private string codeno { get; set; }
: base("{0} is already in use")
public IsUnique (string codeno)
{
this.codeno = codeno;
}
public override ValidationResult IsValid(object value,
ValidationContext vContext)
{
if (value != null)
{
MyDBContext db = new MyDBContext();
Student studentsCodeNo =
db.Students.FirstOrDefault(r => r.codeno== (string)value);
if (studentsCodeNo != null)
{
string errorMessage =
FormatErrorMessage(vContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
As said, the problem is that this version takes parameter. I would like codeno to be read from a user form field, and such value would then be compared against anything in database. I don't know how to read values from the form fields.
Here is code
public class IsUnique : ValidationAttribute{
public override ValidationResult IsValid(object value,
ValidationContext vContext)
{
PropertyInfo property = validationContext.ObjectType.GetProperty("Codeno");
if (property == null)
return new ValidationResult(string.Format("Property '{0}' is undefined","Codeno"));
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
string codeno= (fieldValue == null ? "" : fieldValue.ToString());
if (!string.IsNullOrEmpty(codeno))
{
MyDBContext db = new MyDBContext();
Student studentsCodeNo =
db.Students.FirstOrDefault(r => r.codeno== codeno);
if (studentsCodeNo != null)
{
string errorMessage =
FormatErrorMessage(vContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success; }}
There is sort of an out of the box way to do this already
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.indexattribute(v=vs.113).aspx
[Index(IsUnique=true)]