0

Im trying to write validation in Vaadin but I don't understand how to check if date field is empty

I wrote something like this

    @Override
    public void setConfiguration(EditorConfiguration editorConfiguration) {
    boolean required = ((DateFieldConfiguration) editorConfiguration).isRequired();
    if (required == true) {
        setRequiredIndicatorVisible(true);
        addValueChangeListener(event -> validate(event.getSource().getDefaultValidator(), event.getValue()));

    }

}

    private void validate(Validator<LocalDate> defaultValidator, LocalDate localDate) {

      binder.forField(this).withValidator(validator).asRequired("Mandatory").bind(s -> getValue(),
            (b, v) -> setValue(v));

}

I have achived a validation with a text field:

enter image description here

String Validator code

public class VaadinStringEditor extends TextField implements HasValueComponent<String> {

/**
 * 
 */
private static final long serialVersionUID = 6271513226609012483L;
private Binder<String> binder;

@PostConstruct
public void init() {
    setWidth("100%");
    binder = new Binder<>();
}

@Override
public void initDefaults() {
    setValue("");
    binder.validate();
}

@Override
public void setConfiguration(EditorConfiguration editorConfiguration) {
    Validator<String> validator = ((TextFieldConfiguration) editorConfiguration).getValidator();
    if (validator != null) {
        binder.forField(this).withValidator(validator).asRequired("Mandatory").bind(s -> getValue(),
                (b, v) -> setValue(v));

    }

and I valid it here:

question.setEditorConfiguration(new TextFieldConfiguration(textRequiredValidator()));

Validator:

    private Validator<String> textRequiredValidator() {
    return Validator.from(v -> v != null && StringUtils.trimAllWhitespace((String) v).length() != 0,
            , "Not empty");
}
Anna K
  • 1,666
  • 4
  • 23
  • 47
  • According to the [Vaadin docs](https://vaadin.com/docs/v8/framework/datamodel/datamodel-forms.html#datamodel.forms.validation), once you set your field `asRequired(message)` (or after adding other validators) you can call `binder.validate()` in your _Ok_ button click listener (or whatever you have there). Where did you get stuck? – Morfic Oct 10 '17 at 20:26
  • I dont know how to get LocalDate and check if it is empty or not binder.forField(this).withValidator(validator).asRequired("Mandatory").bind(s -> getValue(), (b, v) -> setValue(v)); Do you know how to write validator for localDate – Anna K Oct 11 '17 at 11:21
  • Did you read the documentation? It's not you who has to check the value. The binder will use the defined validators to check the values, and if all of them pass, then update the value on the bound bean. – Morfic Oct 11 '17 at 11:28
  • Yes but it should be real time validation. I achived that with a text field. So if the text field is empty Im getting a red color label. I will update my question with photo – Anna K Oct 11 '17 at 12:06
  • Maybe you've misunderstood how binder is supposed to work, or maybe you're trying to work around the imposibility of simply defining validators for fields... I can't say for now. How are you going to populate those fields? Do you have a bean, like `Person` with a `name` and `birthday` field? Or some data that is not gouped inside a backing bean? – Morfic Oct 11 '17 at 13:05

1 Answers1

0

You should use com.vaadin.ui.DateField for LocalDate values. Have a look at the following example.

Example bean:

public class MyBean {
    private LocalDate created;

    public LocalDate getCreated() {
        return created;
    }

    public void setCreated(LocalDate created) {
        this.created = created;
    }
}

Editor

DateField dateField = new DateField("Date selector");
binder.forField(dateField)
        .bind(MyBean::getCreated, MyBean::setCreated);

If for some reason you would like to have com.vaadin.ui.TextField for editing date, then you need to set converter like this:

Binder<MyBean> binder = new Binder<>();
TextField textDateField = new TextField("Date here:");
binder.forField(textDateField)
        .withNullRepresentation("")
        .withConverter(new StringToLocalDateConverter())
        .bind(MyBean::getCreated, MyBean::setCreated);

Converter implementation:

public class StringToLocalDateConverter implements Converter<String, LocalDate> {
    @Override
    public Result<LocalDate> convertToModel(String userInput, ValueContext valueContext) {
        try {
            return Result.ok(LocalDate.parse(userInput));
        } catch (RuntimeException e) {
            return Result.error("Invalid value");
        }
    }

    @Override
    public String convertToPresentation(LocalDate value, ValueContext valueContext) {
        return Objects.toString(value, "");
    }
}

Note that this converter does not utilise ValueContext object that contains information that should be taken into account in more complex cases. For example, user locale should be handled.

Mika
  • 1,256
  • 13
  • 18