How to check null values ​​in Wicket Textfield?

I have a Wicket text box that contains an integer value

currentValueTextField = new TextField<IntParameter>("valueText", new PropertyModel<IntParameter>(model, "value"));

I attach a special validator to it, as shown below.

currentValueTextField.add(new IntegerValidator());

Validator class

class IntegerValidator extends AbstractValidator<IntParameter> {

private static final long serialVersionUID = 5899174401360212883L;

public IntegerValidator() {
}

@Override
public void onValidate(IValidatable<IntParameter> validatable) {
    ValidationError error = new ValidationError();
    if (model.getValue() == null) {
        AttributeAppender redOutline = new AttributeAppender("style", new Model<String>("border-style:solid; border-color:#f86b5c; border-width: 3px"), ";");
        currentValueTextField.add(redOutline);
        currentValueTextField.getParent().getParent().add(redOutline);
        validatable.error(error);
        }
    }
}

However, if I do not find anything in the text field, my method is onValidate()not called.

What is the recommended way to check for null values ​​in this case? I would also like to do a range check on the entered value.

+5
source share
4 answers

The default validateOnNullValue()is the default false.

@Override
public boolean validateOnNullValue()
{
     return true;
}

This is the description of the method validateOnNullValue():

, , null. , null,   null ( ). ,  , null  true.

+3

currentValueTextField.setRequired(true);

Wicket . .

, , onError FeedbackBorder .

+4
currentValueTextField.setRequired(true);

. , FeedbackPanel.

+2

The best (and reusable) way to do this is to override the isEnabled(Component)behavior method :

public class HomePage extends WebPage {
    private Integer value;
    public HomePage() {
        add(new FeedbackPanel("feedback"));
        add(new Form("form", new CompoundPropertyModel(this))
            .add(new TextField("value")
                .setRequired(true)
                .add(new ErrorDecorationBehavior()))
            .add(new Button("submit") {
                @Override
                public void onSubmit() {
                    info(value.toString());
                }
            }));
    }
}

class ErrorDecorationBehavior extends AttributeAppender {
    public ErrorDecorationBehavior() {
        super("style", true, Model.of("border-style:solid; border-color:#f86b5c; border-width: 3px"), ",");
    }
    @Override
    public boolean isEnabled(Component component) {
        return super.isEnabled(component) && component.hasErrorMessage();
    }
}
+1
source

All Articles