I created a custom ValidationAttribute that targets a class. This validates correctly whenever I try to call the Validator.TryValidateObject. But when I have other ValidationAttribute in the properties inside my class, the validation results does not contain the result for the class level validation.
Here's a sample code:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class IsHelloWorldAttribute : ValidationAttribute
{
public object _typeId = new object();
public string FirstProperty { get; set; }
public string SecondProperty { get; set; }
public IsHelloWorldAttribute(string firstProperty, string secondProperty)
{
this.FirstProperty = firstProperty;
this.SecondProperty = secondProperty;
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
string str1 = properties.Find(FirstProperty, true).GetValue(value) as string;
string str2 = properties.Find(SecondProperty, true).GetValue(value) as string;
if (string.Format("{0}{1}", str1,str2) == "HelloWorld")
return true;
return false;
}
public override object TypeId
{
get
{
return _typeId;
}
}
}
Here's the code of the class that I need to validate
[IsHelloWorld("Name", "Code", ErrorMessage="Is not Hello World")]
public class MyViewModel : BaseViewModel
{
string name;
string code;
[Required]
public string Name
{
get { return model.Name; }
set
{
if (model.Name != value)
{
model.Name = value;
base.RaisePropertyChanged(() => this.Name);
}
}
}
public string Code
{
get { return code; }
set
{
if (code != value)
{
code = value;
base.RaisePropertyChanged(() => this.Code);
}
}
}
}
Here's how I call the TryValidateObject method:
var validationContext = new ValidationContext(this, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, validationResults, true);
Now, if I have the [Required] attribute in the Name property and I tried to call the Validator.TryValidateObject, the validation result is only one, that's the result for the Required validation. But when I removed the [Required] attribute from the Name and left the IsHellowWorld attribute then called the TryValidateObject, it will give me one result and that's the HellowWorldValidation's result.
What I need to do is to get all the validation on the class level and on the properties level. Can I achieve this without implementing my own TryValidateObject method?