Providing Error Messages

Brightspot provides convenient APIs for displaying data validation and other error messages on the content edit form.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package brightspot.core.miscellaneous;

import com.psddev.cms.db.Content;
import com.psddev.cms.db.ToolUi;
import com.psddev.dari.db.State;

public class Galaxy extends Content {

    private String name;

    @ToolUi.Note("(light years)")
    private String distanceFromEarth;

    protected void beforeSave() {
        try {
            Float.parseFloat(getDistance());
        } catch (NumberFormatException e) {
            State state = getState();
            state.addError(
                 state.getField("distanceFromEarth"),
                 "Distance must be an integer (1234) or a floating-point number (1234.32)");
            throw new IllegalArgumentException("Resolve the errors listed below, then click Publish.");
        }
    }

    public String getDistance() {
        return distanceFromEarth;
    }

}

In the previous snippet—

  • Lines 11–12 declare a field for entering a distance.
  • Lines 14–24 perform data validation prior to saving the object. Brightspot provides several callback methods with which you can perform validation.
    • Line 16 checks if the editor entered a number.
    • Lines 18–21 display a detailed error message above the field distanceFromEarth.
    • Line 22 displays a general error message at the top of the content edit form.
../../../_images/content-edit-form-error-messages.svg

See also: