Constraints and validation

Parent Previous Next

Creating a Car without license number is obviously not reasonable for a vehicle fleet management. As a difference to the int-typed mileage property, the license number is a java.lang.String which cannot be prevented from being set to null by the Java language as such. This is a general challenge, not only for graphical UIs, and was first broadly addressed by the bean validation standard (JSR-303, see for a detailed overview). gengui supports that standard in a way that Bean Validation annotations cause the framework only to accept user input which fulfills the attached constraints.

The following extension of the Car class makes the registration process much saver. You can find the code for this example in directory examples-firststeps/quickstart/validate.

public class Car {

   String licenseNumber;

   Brand brand;

   int mileage;



   @Pattern(regexp="[A-Z]{1,3}\\-[A-Z]{1,3} [1-9][0-9]{0,3}",

       message="German license numbers must be in the form AA-BB ##")

   public String getLicenseNumber() { return licenseNumber; }



   public Brand getBrand() { return brand; }


   // Rest as before


Start the registration for this kind or Cars by the following command:

java gengui.infonode.RootFrame quickstart.validate.RegisterNewCar

The mask looks the same as in the example before but the behavior is different. Click in the field License Number, type "abc", and then press Tab to leave the field. You will see that the field gets marked red and a status message at the bottom of the main window displays a status text according to the message attribute of the violated @Pattern annotation. The message attribute is optional and may also refer to a configuration key for localization. As long as the input is not valid, it is not synchronized from the UI to the underlaying Car object. By default, the framework synchronizes input when ever you change the content of fields or when you press a button (in fact it is a bit more sophisticated - see chapter " Changing the synchronization behaviour" in the manual). Have a look at the button Register. It got disabled now due to invalid input somewhere on the mask. You won't be able to complete the registration process without correcting all fields' content. As soon as you do so, the button gets enabled.

Bean Validation is of course limited to static constraints. If you need a dynamic validation based on your application's state, there are some alternatives, depending on the intended interaction behavior:

Created with the Personal Edition of HelpNDoc: Generate EPub eBooks with ease