Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hello there!
Have you ever encountered these annoying messages that pop up when you typed your input in the wrong format? For example, when you give your mail ID, and @something.com is something they don’t want, you will immediately get a message saying, “Please enter your email in @thisthing.com.” Have you ever typed a decimal number and got a message saying “enter number without ., only whole numbers are valid”?
Reading this article, you will see how to code these messages in our application to get valid inputs that will not affect our data according to the database format.
We will start by learning what validators and converting user inputs are and coding them in the application or web page you will develop. Brace yourselves for the number of codes that are coming your way!
Since this comes under data binding, you will see how to use a binder in these codes.
So first, let us learn what a binder is.
Binder
When you create a form using Vaadin, the text input field defaults to a set field value. So binder helps you to set this fixed validator to the text field the users will use.
Note that you will use forField() and bind() to create the binding to define the field validator. A field validator provides the type of value set to the input field in a form.
Before we jump deep into how to use a binder in code, let’s learn what validators are!
Validators
Validators ensure whether the user has input the correct value type into the input field provided.
The user has to enter the input text as per the setting, like the example I gave above, specifying that the email address should be in “@codingninjas.com,” or the field will not accept it.
We are setting the “@codingninjas.com” email address as a valid id called the validator. So, “@codingninjas.com” is the validator of the text field in the form.
Now that you know how to define a Validator, let us look at how to define one.
How do you define Validators?
There are two ways to define validators:
(i) by using the lambda expression,
(ii) an inline expression, and
(iii) the other is by using a validator instance.
The code in Java below shows how to define validators using the method validator instance:
binder.forField(MyEmail)
//validator instance
.withValidator(new EmailValidator(
“Please provide your mail ID”))
.bind(Person::getEmail, Person::setEmail);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Now let’s see how to define the validator using an inline lambda expression.
binder.forField(MyEmail)
//Lambda based validator
//Returns an error message
.withValidator(
email -> email.endsWith(“@codingninjas.com”),
“Email must be of coding ninjas”)
.bind(Person::getEmail, Person::setEmail);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Although the functions are identical in both code sets, you might have noticed that they have forField() and .bind(). From the above explanations, it is understandable to use a binder to set validators, using forField() and .bind().
forField() acts as a brick used to build the validators and the functions, and .bind() helps bind everything together to provide a better platform for validating the input.
When filling a form, you would have come across the “required” field, meaning filling the field has to be done at any cost. Giving the reason “required” does not make it interesting when users are filling the fields. A message is displayed to make users understand that the field is required. To provide this required field in Vaadin, you use .asRequired() function.
binder.forField(MyEmailField)
// Shortcut for requiring the field to be non-empty
.asRequired(“Please provide your email to proceed.")
.bind(Person::getEmail, Person::setEmail);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Customizing Messages for Validation
Now that it is clear how you can define validators and set messages for incorrect inputs let’s learn how to make them look pretty. Yes, you can add colors and set lengths for information. To display these appealing messages and confirmation messages, you have to use either ValidationStatusHandler or Label for each of the binder blocks you learned how to create earlier.
Let’s not learn how to use both of them, and I will use the same email address validation as the code examples I have been giving from the start.
Using Label :
Label emailError = new Label();
emailError.getStyle().set("color", "Purple");
binder.forField(emailError)
.withValidator(new EmailValidation(
“Please check the email address you have typed in!”))
// Shortcut that updates the label based on the
// status
.withStatusLabel(emailError)
.bind(Person::getEmail, Person::setEmail);
Label emailStatus = new Label();
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Using ValidationStatusHandler:
binder.forField(emailField)
// Define the validator
.withValidator(
email -> email.endsWith(“@codingninjas.com”),
“Only emails with codingninjas.com is valid”)
// Define how the validation status is displayed
.withValidationStatusHandler(status -> {
emailStatus.setText(status
.getMessage().orElse(""));
emailStatus.setVisible(status.isError());
})
// final binding
.bind(Person::getEmail, Person::setEmail);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Sometimes, despite doing all these things, there are chances that the validation fails in the process. An error message can inform the users that the validation has failed. You can use the withStatusLabel(Label label) method.
Adding Multiple Validators
Yes, you read it right! You can add multiple validators and do it; it’s super simple. All you have to do is use .withValidator numerous times. So, now coming to the email address example, you can not only tell the users that the email address is incorrect, but you can also say why it is incorrect.
Even @anything.com can make the email address valid. Still, when you need the email address that contains only @codingninjas.com, you will have to provide two messages, one to say it is incorrect and one to tell why it is false.
binder.forField(emailAddress)
.withValidator(new EmailValidator(
“Sorry, your email address is wrong!”))
.withValidator(
email -> email.endsWith("@codingninjas.com"),
“Only condingninjas.com email addresses are allowed”)
.bind(Person::getEmail, Person::setEmail);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Triggering Revalidation
Have you ever noticed this? When you have to add the month and year of your duration of an academic course or your time working at the company, you have to provide a start and end date. But, you can not swap start and end dates. It has to be one after the other, meaning the end date has to be after the start date. If not, then an error message has to be produced.
Filling one field after the other and the latter field is dependent on the previous area requires revalidation. In this part of the blog, you will learn how to trigger revalidation.
Binder<College> binder = new Binder<>(College.class);
DatePicker StartCourse = new DatePicker();
departing.setLabel("Start Date");
DatePicker EndCourse = new DatePicker();
returning.setLabel("End Date");
// Store returns date binding so that it can be
// revalidated later
Binder.Binding<College, LocalDate> EndCourseBinding =
binder
.forField(EndCourse).withValidator(
EndCourseDate -> !EndCourseDate
.isBefore(SartDate.getValue()),
“You cannot end the course before starting it”)
.bind(College::getEndDate, College::setEndDate);
// Revalidate return date when college start date changes
StartCourse.addValueChangeListener(
event -> EndCourseBinding.validate());
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
The above code gives the error message “You cannot end the course before starting it” when the start date is later than the course’s end date.
Converting User Input
Now you have learned how to validate the user input; you will learn how to convert the user input to the desired data type.
While learning the basics of HTML, you might have come across input data like checkboxes, radio buttons, text fields, and many more.
All the types of input methods have a different way of taking in inputs. A checkbox input type takes in one or more inputs, whereas a radio button takes only one input. The text field takes a character or a whole paragraph as input.
How to define Converters?
Defining converters is pretty similar to defining Validators. For inline lambda expressions, use the callbacks method or Converter Interface.
Let’s look at this example of using CheckBoxes and TextField
CheckBoxes:
Checkbox ageField = new Checkbox("ADULT");
binder.forField(ageField).withConverter(
a -> a? AgeStatus.ADULT : AgeStatus.TEEN,
AgeStatus.ADULT::equals)
.bind(Person::getAgeStatus,
Person::setAgeStatus);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
TextFields:
TextField yearOfStartField =
new TextField("Year of Course Start");
binder.forField(yearOfCourseStartField)
.withConverter(
new StringToIntegerConverter("Not a number"))
.bind(Person::getYearOfCourseStart,
Person::setYearOfCourseStart);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Adding Multiple Converters
Just like using multiple validators, you can also add various converters.
When a form requires the user who has completed the course between 2013 to 2022 for their requirements, they have to ensure that the date they add is within this set of years.
binder.forField(yearOfEndCourseField)
//validator will be run along with the String value
// of the field
.withValidator(text -> text.length() == 4,
“Please enter the year in YYYY format”)
//Converter will only be run for strings
// with 4 characters
.withConverter(new StringToIntegerConverter(
“Must enter the year in YYYY format”))
//validator will be run along with the converted value
.withValidator(year -> year >= 2013 && year < 2022,
“You must have finished the course between 2013 and 2022”)
.bind(Person::getYearOfEndCourseField,
Person::setYearOfEndCourseField);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Converter Interface
A converter interface is a function that converts one type of UI to a different kind of UI. In Java, a converter interface is a class that performs String-to-object to Object-to-string operations and vice–versa.
In Vaadin, it converts from model to presentation and vice versa.
You can use two methods to implement the converter interface:
(i) convertToModel(), which converts and returns the message directly on the screen.
(ii) convertToPresentation(), which converts the input value to the message that has to produce an error message on the screen.
Let us look at an example to know the concept better :
class OurConverter
implements Converter<String, Integer> {
@Override
public Result<Integer> convertToModel(
String fieldValue, ValueContext context) {
// Produces a converted value or an error
try {
// ok, a static helper method that
// creates a Result
return Result.ok(Integer.valueOf(
fieldValue));
} catch (NumberFormatException e) {
// error is a static helper method
// that creates a Result
return Result.error("Enter a name");
}
}
@Override
public String convertToPresentation(
Integer integer, ValueContext context) {
// Converting to the field type should always succeed, so there is no support
// returning an error Result.
return String.valueOf(string);
}
}
// Using the converter
binder.forField(nameField)
.withConverter(new OurConverter())
.bind(Person::getName, Person::setName);
You can also try this code with Online Java Compiler
Note: Use the above code as the syntax, and make the variations according to the variable name you have set.
Frequently Asked Questions
Does the user input in the text field for Validators or Convertors have a default input limit?
There is no character limit on a text field; the limit is endless in the input text field. If you want to set a limitation, you can set it to the required one.
Can the validators and converters be used for any input fields?
Yes, any input field can have validators and converters. Just make sure you enter the type of input correctly onto the code.
Is a binder essential for validating and converting user inputs?
Yes, as discussed above, a binder is necessary for forms, especially as the user input; if it is valid, taken in, and stored in the database by the binder.
It also ensures the correct data is input and compares it to the data format needed.
What is data binding?
Data binding is a library that binds the form's frontend and backend. It technically binds the data with the input area and the database.
Conclusion
Firstly, I appreciate your dedication and patience in learning about Validating and Converting User Inputs. I hope it meets all the requirements you were looking for. I want to express my gratitude to you for reading this article.
In conclusion, the topics explained in this article are what is validators and how to set validators for user input. What does Converter means, and how to fix it for user inputs? How to style the error messages and edit them? And lastly, how to implement the converter interface.