I have a spring boot application with Vaadin and I just need simple UI element validation without backing beans.For example to just check if a textfield value is null,empty or not.
Since validators require a bean I was thinking of using Junit Assert for this simple job. So using Junit not just for running tests but for the main flow of the application.
Is this good practice and what alternatives are there?
CodePudding user response:
For such use cases where you need to bind Vaadin's Converters or Validators to a single field / value pair without a Bean being involved I have written FieldBinder utility class, which can be found in Vaadin's Directory and added as maven dependency to your project.
https://vaadin.com/directory/component/fieldbinder
// Binder with integer
FieldBinder<Integer> integerFieldBinder = new FieldBinder<>();
TextField integerField = new TextField("Input number");
// Text field with Integer value Converter and Validator
// Demoing how to detect if value is valid and how to get it from FieldBinding
FieldBinding<Integer> integerBinding = integerFieldBinder.forField(integerField)
.withConverter(new StringToIntegerConverter("This is not a number"))
.withValidator(new IntegerRangeValidator("Give a number between 5 and 10",5,10))
.bind(integerValue);
CodePudding user response:
Is this good practice
I don't think junit is meant to be used in a production code
I just need simple UI element validation without backing beans. what alternatives are there
I believe you can still use the binding API, just ignore getters/setters:
new Binder<>().forField(new TextField())
.withValidator(...)
.bind(o -> null, (o, o2) -> {});
CodePudding user response:
While a "bean" is needed for the Binder
it does not have to be
a something fully drawn out. You can also bind
with two functions (a
ValueProvider
and a Setter
). With this you can basically use any
container you like as "bean". E.g. a Map
or an AtomicInteger
(you
must have means to read a value from it and write a value back).
def tf = new TextField("Answer to all questions of the universe").tap {
setWidthFull()
}
def binder = new Binder<Map>().tap{
forField(tf)
.asRequired("A value is mandatory")
.withNullRepresentation("")
.withConverter(new StringToIntegerConverter("Only numbers are allowed"))
.withValidator(new IntegerRangeValidator("Must be 42", 42, 42))
.bind( // XXX
{ m -> m.value },
{ m, v -> m.value = v }
)
setBean([:])
}
add(tf)
add(new Button("Save", {
Notification.show(binder.valid ? "Saved ${binder.bean}" : "Please fix the errors first")
}))