4
votes

I played around with nhibernate validator and got a nearly perfect solution.

I can define a property to be validated and it's done on pre-save. But I have some cases where it's not working.

Let's assume I have an object called person and via nhibernate I mapped the address(also an object) to be a property of person (in fact it's a list of addresses).

When I save the person my address is not validated.

The form to enter the information is made out of partial forms. Would be nice if the address validation could be added to the person's validation list, but thats not required.

I need a general solution, I cannot validate by "hand" e.g. if person then validate address... Somehow the validator should see that there is an object behind the property which I also have to validate.

Update: What I am looking for is a way to validate mapped objects (hasmany).

2
Can you post up some of your source code, in particular how the validator is attached to the column/collection of interest? - Jon Seigel
In the class where I have the properties nhibernate validator lets me define something like [NotNullNotEmpty(Message = "Foofield: Please fill in something.")] public virtual string foofield {get;set;} Let's say I have a class person and there a class address. So I map in the person's class hasmany<address>, on saving the person the addresses are not validated. If I call save on each of them they are validated... But that is definitely not the solution ;) - griti

2 Answers

1
votes

If you're trying to put input validation in these classes, which is what I think you're trying to do, I would advise against it, as this is business logic. Anything you'll find in Hibernate that does this is only doing it to ensure constraints in the database (i.e., a not-null column).

What I would recommend is that you create a utility class or method to do the input validation for you. If you need to add database constraints to the entity properties, by all means do that, but I would not rely on them for input validation.

1
votes

After switching to the newest release of nhibernate validator the validation works for subclasses and mapped classes. Together with xVal 1.0 it's a very satisfying solution.

Now I can define on every property against what it should be validated (e.g. for a regex, length etc...) and I get the message on client side via xVal, on server side via nHibernate Validator. In fact they share the validation pattern and the error messages.

I would recommend this for any nHibernate-Project where a simple definition for validation and messaging is required.