Answer the question
In order to leave comments, you need to log in
Structure self-validation error?
I'm self-validating a struct and running into a
DataAnnotations ArgumentException The provided instance must match the ObjectInstance in the provided ValidationContext.
There is an implementation of the interface, but how exactly to use it?
so that the fields of the structure attributes can be checked automatically
public struct TableData : IValidatableObject
{
public string description;
public string[] words;
public string GetIndexedWords(int i, int j)
{
return words[i * 10 + j];
}
public void SetIndexedWords(string word, int i, int j)
{
words[i * 10 + j] = word;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
ValidationResult error = null;
if (String.IsNullOrWhiteSpace(description))
{
error = new ValidationResult("Поле description не инициализировано или является пустой строкой");
goto TORETURN;
}
if (words == null || words.Length != 100)
{
error = new ValidationResult("Поле words не инициализировано или не имеет длинну 100");
goto TORETURN;
}
for (int i = 0; i < 100; i++)
{
if (String.IsNullOrWhiteSpace(words[i]))
{
error = new ValidationResult($"Элемент words[{i}] не инициализирован или является пустой строкой");
goto TORETURN;
}
}
TORETURN:
return new List<ValidationResult>() { error };
}
}
Answer the question
In order to leave comments, you need to log in
mb because you have a structure?
it is copied - so the original instance does not match the one captured in the validation context
public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults, bool validateAllProperties) {
if (instance == null) {
throw new ArgumentNullException("instance");
}
if (validationContext != null && instance != validationContext.ObjectInstance) {
throw new ArgumentException(Resources.DataAnnotationsResources.Validator_InstanceMustMatchValidationContextInstance, "instance");
}
bool result = true;
bool breakOnFirstError = (validationResults == null);
foreach (ValidationError err in GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError)) {
result = false;
if (validationResults != null) {
validationResults.Add(err.ValidationResult);
}
}
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question