aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/data/validator/NullValidator.java
blob: 551d88c776a0d9d1f6399d7d841265511f3725b0 (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* 
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.data.validator;

import com.vaadin.data.Validator;

/**
 * This validator is used for validating properties that do or do not allow null
 * values. By default, nulls are not allowed.
 * 
 * @author Vaadin Ltd.
 * @version
 * @VERSION@
 * @since 3.0
 */
@SuppressWarnings("serial")
public class NullValidator implements Validator {

    private boolean onlyNullAllowed;

    private String errorMessage;

    /**
     * Creates a new NullValidator.
     * 
     * @param errorMessage
     *            the error message to display on invalidation.
     * @param onlyNullAllowed
     *            Are only nulls allowed?
     */
    public NullValidator(String errorMessage, boolean onlyNullAllowed) {
        setErrorMessage(errorMessage);
        setNullAllowed(onlyNullAllowed);
    }

    /**
     * Validates the data given in value.
     * 
     * @param value
     *            the value to validate.
     * @throws Validator.InvalidValueException
     *             if the value was invalid.
     */
    @Override
    public void validate(Object value) throws Validator.InvalidValueException {
        if ((onlyNullAllowed && value != null)
                || (!onlyNullAllowed && value == null)) {
            throw new Validator.InvalidValueException(errorMessage);
        }
    }

    /**
     * Returns <code>true</code> if nulls are allowed otherwise
     * <code>false</code>.
     */
    public final boolean isNullAllowed() {
        return onlyNullAllowed;
    }

    /**
     * Sets if nulls (and only nulls) are to be allowed.
     * 
     * @param onlyNullAllowed
     *            If true, only nulls are allowed. If false only non-nulls are
     *            allowed. Do we allow nulls?
     */
    public void setNullAllowed(boolean onlyNullAllowed) {
        this.onlyNullAllowed = onlyNullAllowed;
    }

    /**
     * Gets the error message that is displayed in case the value is invalid.
     * 
     * @return the Error Message.
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * Sets the error message to be displayed on invalid value.
     * 
     * @param errorMessage
     *            the Error Message to set.
     */
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

}