Rules Engine – Managing Client and Server Side Validation

Architecturedsljavajavascript

Has anyone managed to use a common rules system between their frontend and backend?

Similar to this question:
Managing client-side and server-side validations in one place, I'm trying to find a way to have consistent business rules applied on the front (JS) and back end (Java). Unlike this question though, I'm not interested in a general cross-platform field validation system (I'm not out to validate the field length).

An example of a business rule can be something like:

If the user's age is under 18, then a parent's email is required.

In this case the nullability of a form field changes based on input from another part of the form.

So that the system would allow:

{"user":"Bob","age":33}

{"user":"Carol","age":15,"parent_email":"foo@bar.com"}

But deny:

{"user":"Alice","age":16}

A rules engine like Drools can create and apply business rules on the backend, but only in a JVM (or CLR).

The default solution seems to be having two different sets of rules which will never stay in sync and cause all kinds of validation problems and edge cases.

I'd love to hear some successes, failures, or better techniques for tackling this problem.

Best Answer

This is related to constraint-programming. Prolog is an example of such a system. There exists javascript implementations of prolog http://yieldprolog.sourceforge.net/ . You could then make your prolog program and use it on both the server and client.

Another approach is having all the logic on the server side but expose it as an api which the client could then query using ajax. It would feel almost the same to the user with the exception of a possible small delay.