Search code examples
c#.netwpfidataerrorinfo

Localize Data validation errors


When I use:

[Required(ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "MessageIISPathRequired")]
[CustomValidation(typeof (IISVM), "WebsiteRootExists", ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "MessageIISPathInvalid")]
public string WebsiteRoot
{
    get { return _data.WebsiteRoot; }
    set { SetProperty("WebsiteRoot", () => _data.WebsiteRoot == value, () => _data.WebsiteRoot = value); }
}

I get a null message and in my resources file the message is there and it is public. This is not an MVC app it is a WPF desktop application and all my validations were working until I converted it to use the resources.

I think it has to do with how I grab the errors:

private static ValidationAttribute[] GetValidations(PropertyInfo property)
{
    return property.GetCustomAttributes(typeof (ValidationAttribute), true) as ValidationAttribute[];
}

private static Func<IISVM, object> GetValueGetter(PropertyInfo property)
{
    LinqExpress.ParameterExpression instance = LinqExpress.Expression.Parameter(typeof (IISVM), "i");
    LinqExpress.UnaryExpression cast =
        LinqExpress.Expression.TypeAs(LinqExpress.Expression.Property(instance, property),
                                      typeof (object));
    return (Func<IISVM, object>) LinqExpress.Expression.Lambda(cast, instance).Compile();
}

And my IDataErrorInfo implementation

public string this[string columnName]
{
    get
    {
        if (PropertyGetters.ContainsKey(columnName))
        {
            object value = PropertyGetters[columnName](this);
            string[] errors =
                Validators[columnName].Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage).ToArray();
            return string.Join(Environment.NewLine, errors);
        }

        return string.Empty;
    }
}

Solution

  • Issue fixed. I had to use reflection and try to validate the property when the method was called instead of trying to calculate it with the static methods above.

    if (PropertyGetters.ContainsKey(columnName))
                {
                    ValidationContext context = new ValidationContext(this, null, null)
                    {
                        MemberName = columnName
                    };
    
                    List<ValidationResult> results = new List<ValidationResult>();
                    var value = GetType().GetProperty(columnName).GetValue(this, null);
    
                    return !Validator.TryValidateProperty(value, context, results)
                               ? string.Join(Environment.NewLine, results.Select(x => x.ErrorMessage))
                               : null;
                }
    
                return null;