-
Notifications
You must be signed in to change notification settings - Fork 0
Validation
pramode edited this page Jun 26, 2011
·
3 revisions
Here is the controller action;note that we are using annotations for validation
public static void fun(@Required(message="Name is required") String name,
@Required(message="Age is required and should be >= 10") @Min(10) int age) {
render(name, age);
}
And here is the template:
#{extends 'layout1.html' /}
#{set title:'Testing validation' /}
#{ifErrors}
<h1>Oops!</h1>
#{errors}
<li>${error}</li>
#{/errors}
#{/ifErrors}
#{else}
Hello ${name}, your age is ${age}
#{/else}
Read the official doc. It involves using params.flash() and validation.keep(). The first one stores http parameters in the "flash" and the second one makes the errors available in the next request. These are done using cookies.
Check out official doc for a number of built-in validations.
We have a "model" class:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import play.data.validation.*;
@Entity
public class Client extends Model {
@Required(message="Name is required")
public String name;
@Required
@Min(10)
public int age;
}
Note that we are annotating the fields with validations.
Now, we have a controller task:
public static void fun(@Valid Client c) {
if(validation.hasErrors())
System.out.println("error in validation");
render(c);
}
The @Valid says that all the annotations in Client have to be verified.
Now, we have the template:
#{extends 'layout1.html' /}
#{set title:'Testing validation' /}
#{ifErrors}
<h1>Oops!</h1>
#{errors}
<li>${error}</li>
#{/errors}
#{/ifErrors}
#{else}
Hello ${c.name}, your age is ${c.age}
#{/else}