1
Vote

NHibernate.Validator ValidAttribute not supported

description

The NHibernateValidatorRulesProvider class does not support the NHibernate.Validator ValidAttribute because it does not implement NHibernate.Validator.Engine.IRuleArgs.
 
Client model code:
 
public class User : Entity<int>
{
[NotNullNotEmpty()]
public virtual string Forename { get; set; }

public virtual string Surname { get; set; }

[Valid]
public virtual UserCredentials Credentials { get; set; }
}

public class UserCredentials
{
[NotNullNotEmpty()]
[Email]
public virtual string Email { get; set; }

[NotNullNotEmpty()]
public virtual string Password { get; set; }
}
 
Solution (This works for me, but there's probably a more elegant way):
 
namespace xVal.RulesProviders.NHibernateValidator
{
public class NHibernateValidatorRulesProvider : CachingRulesProvider
{
    ...

    protected override RuleSet GetRulesFromTypeCore(Type type)
    {
        var classMapping = ClassMappingFactory.GetClassMapping(type, configMode);

        var rules = (from member in type.GetMembers()
                where member.MemberType == MemberTypes.Field || member.MemberType == MemberTypes.Property
                from att in classMapping.GetMemberAttributes(member).OfType<IRuleArgs>() // All NHibernate Validation validators attributes must implement this interface
                from rule in ConvertToXValRules(att)
                where rule != null
                select new { MemberName = member.Name, Rule = rule }).ToList();

        // ValidAttribute does not implement IRuleArgs
        var embeddedTypes =
            from property in type.GetProperties()
            where property.GetCustomAttributes(typeof(ValidAttribute), false).Length > 0
            select property.PropertyType;

        foreach (var embeddedType in embeddedTypes)
        {
            RuleSet rs = GetRulesFromTypeCore(embeddedType);
            foreach (string key in rs.Keys)
            {
                rules.AddRange(rs[key].Select(x => new { MemberName = key, Rule = x }));
            }
        }

        return new RuleSet(rules.ToLookup(x => x.MemberName, x => x.Rule));
    }
    ...
}
}
 
A better write-up can be found here: http://www.triggerfishsoftware.co.uk/blog/xval-and-nhibernate-validator-validattribute

comments