我试图在Vaadin中编写验证,但我不明白如何检查日期字段是否为空
我写了这样的东西
@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));
}
我已经通过文本字段进行了验证:
字符串验证器代码
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));
}
我在这里有效:
question.setEditorConfiguration(new TextFieldConfiguration(textRequiredValidator()));
验证
private Validator<String> textRequiredValidator() {
return Validator.from(v -> v != null && StringUtils.trimAllWhitespace((String) v).length() != 0,
, "Not empty");
}
答案 0 :(得分:0)
您应该com.vaadin.ui.DateField
使用LocalDate
值。看看下面的例子。
示例bean:
public class MyBean {
private LocalDate created;
public LocalDate getCreated() {
return created;
}
public void setCreated(LocalDate created) {
this.created = created;
}
}
编辑
DateField dateField = new DateField("Date selector");
binder.forField(dateField)
.bind(MyBean::getCreated, MyBean::setCreated);
如果由于某种原因你希望com.vaadin.ui.TextField
有编辑日期,那么你需要像这样设置转换器:
Binder<MyBean> binder = new Binder<>();
TextField textDateField = new TextField("Date here:");
binder.forField(textDateField)
.withNullRepresentation("")
.withConverter(new StringToLocalDateConverter())
.bind(MyBean::getCreated, MyBean::setCreated);
转换器实施:
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, "");
}
}
请注意,此转换器不使用ValueContext对象,该对象包含在更复杂的情况下应考虑的信息。例如,应该处理用户区域设置。