How to bind TextField with duplicate entry validator

Hello i’m Ical.

I’ve been looking for some validation regarding vaadin data binding but, I’m still confused about duplicate entry validation on vaadin. I’m new on vaadin so i hope someone can explain it in detail and clearly.

Thank you

Hi,

a couple of questions:

  • Which version of Vaadin are you using?
  • Can you give an example of what you mean by “duplicate entry validation”?

-Olli

Olli Tietäväinen:
Hi,

a couple of questions:

  • Which version of Vaadin are you using?
  • Can you give an example of what you mean by “duplicate entry validation”?

-Olli

  • Im using Vaadin 8
  • What I mean is, when user input the same name that’s already exist in database, there is a validator that’s keep the user from saving the data

Thanks

Check out the documentation here: https://vaadin.com/docs/v8/framework/datamodel/datamodel-forms.html

In the chapter “Validating and Converting User Input”, you will see an example of three different validation scenarios. In the middle one, it’s doing a custom validation like this:

binder.forField(nameField)
  // Validator defined based on a lambda and an error message
  .withValidator(
    name -> name.length() >= 3, // <--- this is the relevant part
    "Full name must contain at least three characters") // error message if validation fails
  .bind(Person::getName, Person::setName);

The first parameter to the withValidator method call is a lambda expression in this case. The lambda takes the text from the input field (the variable name name is used here) and checks that its length is at least three characters long. In a similar manner, you can check your backend that the name doesn’t exist and return true if so. Something like this:

binder.forField(yourTextField)  
  .withValidator(
    inputText -> yourBackend.nameIsUnique(inputText),
    "Name must be unique")
  .bind(/* ... */);

Sorry Olli, Can you show me what is inside nameIsUnique?

You will need to implement it yourself, based on your backend. It could be a database query or something. It just needs to be a method that returns a boolean and takes a String parameter (in this example situation).

-Olli

Thank you very much Olli, I found a way to do that.

Great!

Raynaldi Faizal:
Thank you very much Olli, I found a way to do that.

Can you please help how did you do that?