Reputation: 8357
I have a C# WinForms application where multiple objects in a collection need to be valid before functions can be called in each object.
I have done some research and there is a ValidationResult class. Is this class suitable for returning validation data about an object, such as some properties are null, or is there another specific class that should be used?
Upvotes: 0
Views: 9409
Reputation: 5683
You can use the RequiredAttribute
from the System.ComponentModel.DataAnnotations
namespace. Put this attribute on top of a property to validate if it's not null like so:
using System.ComponentModel.DataAnnotations;
public class MyDto
{
[Required]
public SomeObject SomeProperty { get; set; }
}
Likewise you can use more validation attributes from this namespace.
You can also create your own validation attributes if you inherit from ValidationAttribute
. For example a Validation attribute that validates every object inside a list, something like:
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class ValidateCollectionAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var collection = value as IEnumerable;
if (collection != null)
{
foreach (object element in collection)
{
//do validation
}
}
return ValidationResult.Success;
}
}
Next you can use the Validator
class to validate your object. You need to create a ValidationContext where you put your instance into, like so:
var instance = new MyDto { SomeProperty = null }; //note that I'm setting the property to null, while the property has the Required attribute
var context = new ValidationContext(instance);
var validationResults = new List<ValidationResult>(); //this list will contain all validation results
Validator.TryValidateObject(instance, context, validationResults, validateAllProperties: true);
var errors = validationResults.Where(r => r != ValidationResult.Success); //filter out all successful results since we are only interested in errors
if (errors.Any())
{
//do whatever you like to do
}
Since I've instantiated the MyDto
object with null
for it's property, the Validator
will return a ValidationResult
that's been triggered by the Required
attribute.
You could create a service that executes this kind of code, or you could just hard-wire this inside your code-behind. Whatever floats your boat.
Upvotes: 1