Reputation: 211
I have a custom validation attribute which isn't triggering. Please refer to the following code for more details.
public HttpResponseMessage GetTestResponse()
{
var model = new TestClass1()
{
Id = 1,
address = new Address() { StreetName = "test" }
};
bool validateAllProperties = false;
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(
model,
new ValidationContext(model, null, null),
results,
validateAllProperties);
if (isValid)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest);
}
}
public class TestClass1
{
public string Name { get; set; }
[Required,Range(1,5)]
public int Id { get; set; }
[Required]
[ValidateObject("StreetNumber is required")]
public Address address { get; set; }
}
public class Address
{
[Required]
public int? StreetNumber { get; set; }
public string StreetName { get; set; }
}
public class ValidateObjectAttribute : ValidationAttribute
{
public ValidateObjectAttribute(string errorMessage)
{
ErrorMessage = errorMessage;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(value, null, null);
Validator.TryValidateObject(value, context, results, true);
if (results.Count != 0)
{
var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
}
public class CompositeValidationResult : ValidationResult
{
private readonly List<ValidationResult> _results = new List<ValidationResult>();
public IEnumerable<ValidationResult> Results
{
get
{
return _results;
}
}
public CompositeValidationResult(string errorMessage) : base(errorMessage) { }
public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }
protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }
public void AddResult(ValidationResult validationResult)
{
_results.Add(validationResult);
}
}
The custom attribute not triggering and the isvalid returning true, which should be false as one of the property inside Address class is required and is not being provided. Is there a a piece missing that I should be adding in order to make this work?
Upvotes: 1
Views: 1294
Reputation: 8809
The example appears to be missing this part:
Make the class not inheritable. Add the
NotInheritable
keyword in Visual Basic or thesealed
keyword in Visual C#.e.g.:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] sealed public class CustomAttribute : ValidationAttribute { }
REF: How to: Customize Data Field Validation in the Data Model Using Custom Attributes
Upvotes: 1