[JAVA] Validation function in Play Framework

In this post, I would like to write about implementing the validation function using the Play Framework. The source can be found on GitHub.


To realize the validation function by using the parts of Play Framework. I would like to check the input items from the form screen and display an error message on the screen if the input items are not valid.


validation The validation function is indispensable for web applications to verify the validity of the data input from the screen. Many frameworks are equipped with parts that support the realization of validation functions by default, and there are also highly functional and convenient parts in the Play Framework. I implemented the validation function using them. The file structure is as follows.

    ├── app
    │   ├── checks
    │   │   ├── Check.java
    │   │   ├── IndexCheck.java
    │   │   └── unit
    │   │       ├── EqualsCheck.java
    │   │       ├── ManagerLimitCheck.java
    │   │       └── UnitCheck.java
    │   ├── common
    │   │   └── constants
    │   │       └── Job.java
    │   ├── controllers
    │   │   └── AppController.java
    │   ├── forms
    │   │   └── IndexForm.java
    │   └── views
    │       ├── formTable.scala.html
    │       ├── index.scala.html
    │       ├── main.scala.html
    │       └── tableRowInput.scala.html
    ├── conf
    │   ├── messages
    │   └── routes
    └── public
        └── stylesheets
            └── main.css

Basically, it is the default configuration of Play, but I made a package called checks and tried to have data validation logic that can not be picked up by annotation.

This time I would like to touch on Form and View.

Form I have a Form class in forms. There are other frameworks that can check a single item just by adding annotation to the parameter of Form, but Play has the same function. There is a package called play.data.validation.Constraints, which allows you to perform mandatory checks, character count checks, regular expression checks, etc., so checking for single items is almost complete. I made IndexForm.java with items that are likely to be common.


public class IndexForm {
	public String name;
	@Min(value=15, message="Please enter at least 15 years old")
	@Max(value=55, message="Please enter under 55 years old")
	public Integer age;
	/**mail address*/
	public String email;
	@Pattern(value="^[0-9a-zA-Z]*$", message="Please enter only alphanumeric characters")
	public String password;
	/**Re-enter password*/
	public String againPassword;
	@Required(message="Must be selected")
	public String job;

	 *Validity check of input data
	 * @return error information
	public List<ValidationError> validate(){
		List<ValidationError> errors = new ArrayList<>();
		IndexCheck check = new IndexCheck();
		check.execute(this, errors);
		return errors;


The * validate () method is called when binding the input value to the Form, and implements validation validation that was not picked up by annotation. Checks is an original implementation that has nothing to do with the Play Framework features, so I won't cover it in this post, but if you have time, please take a look and use it as a reference (or point out). *

Each annotation effect is as follows

--Required: Required check --Max: Numerical upper limit check --Min: Numerical lower limit check --MaxLength: Check the maximum number of characters --MinLength: Check the lower limit of the number of characters --Pattern: Regular expression check --Email: Email address check

There are other useful things, so it's a good idea to take a look at Constraints. However, it is very convenient that validation for a single item can be implemented with just this. The message you want to output when an annotation error occurs is defined in an external file, and that is conf / messages. Those that pass arguments have their annotation-specific settings.


error.required =Required
error.invalid =Please enter in the correct format
error.max = {0}Please enter by age
error.email =Please enter your e-mail address
error.minLength = {0}Please enter more than one character
error.maxLength = {0}Please enter the characters below

That way, you can define the message by default. If you do not pass any arguments, you will use this error message. If it is not defined here, the message defined by default in Play will be used. error.invalid is an error message when the input value cannot be bound to the Form parameter due to a wrong type and fails.

View In Play Framework, so-called dynamic html called scala.html plays the role of the view part. Below is index.scala.html that just arranges the input tags of the form with the table tags. ..


@(playForm: Form[forms.IndexForm])

@import collection.JavaConversions._
@import helper._

@main("Validation Test") {
    <h1>Form screen</h1>
    @form(action = routes.AppController.post()) {
                '_label -> "name"
            )(tableRowInput, implicitly[Messages])

                '_label -> "age",
                'placeholder -> "15-55 years old"
            )(tableRowInput, implicitly[Messages])

                '_label -> "mail address"
            )(tableRowInput, implicitly[Messages])

                '_label -> "password",
                'placeholder -> "Alphanumeric only"
            )(tableRowInput, implicitly[Messages])

                '_label -> "Re-enter password"
            )(tableRowInput, implicitly[Messages])

                options = common.constants.Job.getMap().toSeq,
                '_label -> "Profession"
            )(tableRowInput, implicitly[Messages])


Play has a views.html.helper package that generates html tags pretty well. You can understand more about helper by referring to the Official Page. By using helper, you can easily link with Form on Java side. There is a default for the template generated by helper, but here I wanted to output the table tag, so [tableRowInput](https://github.com/hys-rabbit/PlayValidation/blob/master/app/views/ I made my own tableRowInput.scala.html) and used it as a template.

Operation check

Now, I would like to actually run the server and see the screen. スクリーンショット 2017-03-19 12.34.16.png

Click the "Send" button スクリーンショット 2017-03-19 12.34.16.png

The message will be displayed properly.


You don't necessarily have to use the framework features, but considering productivity and maintenance, I think you should adopt the framework features as much as possible. Rather, I don't understand the meaning of using the framework without using the functions of the framework. If you are an engineer who adopts Play for new development, I would like you to design by taking advantage of Play's functions.


Recommended Posts

Validation function in Play Framework
Authentication function in Play Framework [Access restrictions]
Play Framework 2.6 (Java) environment construction in Eclipse
Authentication function with Play Framework [Registration and authentication]
Play Framework study
Handle JSON in cross domain with Play Framework
Play Framework studying test
play framework personal notes
Implement application function in Rails
Play Framework Study Memo Database ①
Java to play with Function
About validation methods in JUnit
First Play Framework personal notes
Introduced Dozer to Play Framework
If the submodule assets are not found in the Play Framework
A story stuck with log output in Docker + Play framework environment
Use voice recognition function in Unity
Play Framework Study Memo Database ②Read
Add a search function in Rails.
[Rails] Unexpected validation error in devise
Play Framework 2.6 (Java) development environment creation
Play Framework Study Momo DB Update
Implement simple login function in Rails
Implement tagging function in form object
Implement PHP implode function in Java
Enables ActiveModel-equivalent validation in ActiveRecord (before_type_cast)
Implement CSV download function in Rails
Play with Markdown in Java flexmark-java
Error encountered in tagging function implementation
Implementation of like function in Java