Validating HTTP data with Play

Source: Internet
Author: User

Validations ensure the data has certain values or meets specific requirements. You can use validation to verify that your models is correct before saving them to the database, or use them directly on HTTP parameters to validate a simple form.

How validation works in Play

Each request has it own Validation object which collects errors. There is three ways to define validations.

    1. In a controller method, call methods on the controller ' s validation field directly. You can also access a subset of the API using the play.data.validation.Validation class ' static methods.
    2. ADD validation Annotations to the Controller method ' s parameter declarations.
    3. Add the @Valid annotation to action methods ' POJO parameters, and add validation annotations to the POJO Properti Es.

The validation object maintains a collection of play.data.validation.Error objects. Each error has both properties:

    • The key. This helps determine which data element caused the error. The key value can be set arbitrarily if Play generates errors, it uses default conventions that follow the Java vari Ables ' names.
    • The message. This contains the error ' s textual description. The message can be a plain message or refer to a key from a message bundle (typically for internationalization support).

Using The first approach, let's see if validate a simple HTTP parameter:

public static void hello(String name) {     validation.required(name);     …}

This code checks, the name variable is correctly set. If not, the corresponding error was added to the current Errors collection.

You can repeat this operation for each validation you need:

public static void hello(String name, Integer age) {     validation.required(name);     validation.required(age);     validation.min(age, 0);     …}
Validation error Messages

At the end of the validation you can check if any errors has been created and display them:

public static void hello(String name, Integer age) {     validation.required(name);     validation.required(age);     validation.min(age, 0);          if(validation.hasErrors()) {         for(Error error : validation.errors()) {             System.out.println(error.message());         }     }}

Assuming. Name and age is null, this would display:

RequiredRequired

Because the default message, defined in $PLAY _home/resources/messages, is:

validation.required=Required

There is three ways to customise the validation message.

    1. Override the default message, by redefining the message in your application ' s messages file.
    2. Provide a custom message as an additional validation parameter.
    3. Provide a message key for a localised message as an additional validation parameter.
Localised validation messages

The simplest-on-the-these-messages is-to-use the same message key-a message in your application ' s conf/me Ssages file. For example:

You can also provide localisations on other languages, as described in internationalization.

Validation Message Parameters

You can use a placeholder of the message for the error key:

validation.required=%s is required

This changes the output to:

name is requiredage is required

This error key defaults to the parameter name, and was itself used to look up a message. For example, the name parameter in the the Hello action method above could is localised with:

name = Customer name

This would result in the output:

Customer name is requiredage is required

You can change also override the error key using the error.message (String Key) method. For example:

Error error = validation.required(name).error;if(error != null) {    System.out.println(error.message("Customer name"));}

Several of the built-in validations define additional message parameters that correspond to the validation parameters. For example, the ' match ' validation defines a second String parameter for the specified regular expression, which differs from the %s placeholder above on that it specifies the parameter index ' 2 ':

Similarly, the ' range ' validation defines, additional numeric parameters, with indices 2 and 3:

Look in the file $PLAY _home/resources/messages to see which other validations has parameters.

Custom Localised validation messages

The validation messages in $PLAY _home/resources/messages with the default message key for each of the PLAY ' s built-in Validations. You can specify a different message key. For example:

Use this new message key for the message, for manual validation in the action method:

Alternatively, use the key in the annotation ' s message parameter:

public static void hello(@Required(message="validation.required.em") String name) {    

You can use the same technique with validation annotations on JavaBean properties:

public static void hello(@Valid Person person) {    …}  public class Person extends Model {    @Required(message = "validation.required.emphasis")   public String name;    
Custom literal (non-localised) validation messages

The Play message look-up just returns the message key if there is no message defined for the key, which means you can also Just use a literal message instead of the message key if you prefer. Using the same examples as above, for manual validation:

For action method parameter annotations:

public static void save(@Required(message = "Give us a name!") String name) {    

For JavaBean property Annotations:

public static void save(@Valid Person person) {    …} public class Person extends Model {   @Required(message = "Give us a name!")   public String name;    
Displaying validation errors in the template

The cases want to display of the error messages in the view template. You can access them in the template using the errors object. Some tags help your To display the errors:

Let's see a sample:

public static void hello(String name, Integer age) {   validation.required(name);   validation.required(age);   validation.min(age, 0);   render(name, age);}

And now the template:

#{ifErrors}    

But in a real application your want to redisplay the original form. So you'll have a actions:one to display the form and a another one to handle the POST.

Of course the validation would occur in the second action and if some error occurs you'll have to redirect to the first A Ction. Need a special trick to keep your errors during the redirect. Use the validation.keep () method. This would save the Errors collection for the next action.

Let's see a real sample:

public class Application extends Controller { public static void index() { render(); } public static void hello(String name, Integer age) { validation.required(name); validation.required(age); validation.min(age, 0); if(validation.hasErrors()) { params.flash(); // add http parameters to the flash scope validation.keep(); // keep the errors for the next request index(); } render(name, age); } }

And the view/application/index.html Template:

#{ifErrors} 

You can create a better user experience by displaying each error message next to the field that generated the error:

#{ifErrors} 
Validation annotations

The annotations in the play.data.validation package provide a alternative and more concise A-to specify Valida tion constraints, with a annotation that corresponds to each Validation object method. To use the validation annotations, just annotate the controller method parameters:

public static void hello(@Required String name, @Required @Min(0) Integer age) {   if(validation.hasErrors()) {       params.flash(); // add http parameters to the flash scope       validation.keep(); // keep the errors for the next request       index();   }   render(name, age);}
Validating Complex objects

You can also use the validation annotations-easily add constraints to your model object's properties, and then in the C Ontroller specify that all properties must is valid. Let ' s rewrite the previous example using a User class.

First the User class, with validation annotations on the properties:

package models; public class User {        @Required    public String name;     @Required    @Min(0)    public Integer age;}

Then the modified Hello action, which uses the @Valid annotation To specify so all of the USERobject ' s properties must be valid:

public static void hello(@Valid User user) {   if(validation.hasErrors()) {       params.flash(); // add http parameters to the flash scope       validation.keep(); // keep the errors for the next request       index();   }   render(name, age);}

And finally the modified form:

#{ifErrors}   
Built-in validations

The play.data.validation package contains several built-in validations so can use on thevalidation object or with annotations.

Custom validation

Can ' t find the validator you need in the play.data.validation package? Write your own. You can use the generic @CheckWith annotation to bind your own Check implementation.

For example:

public class User {        @Required    @CheckWith(MyPasswordCheck.class)    public String password;        static class MyPasswordCheck extends Check {                public boolean isSatisfied(Object user, Object password) {            return notMatchPreviousPasswords(password);        }            }}

Continuing the discussion

The last layer of a Play application: Domain object model.

Validating HTTP data with Play

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.