英文对照 介绍Play Framework 框架 验证

lyuehh 发布于 2010/07/31 14:43
阅读 1K+
收藏 4

使用Play验证HTTP数据

h1. Validating HTTP data with Play

 

验证确保数据有确定的值,或者符合某种特殊的需求,你可以在模型被保存进数据库之前使用验证去核实你的模型,或者直接在HTTP参数中使用它们去验证一个简单的form表单。

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

 

它们怎样工作?

h2. <a>How does it work?</a>

 

每一次的请求使用它自己的验证去收集错误。在控制器里,你可以直接使用Validation变量,你也可以直接访问play.data.validation.Validation类下的API中的静态方法。

Each request has it own **Validation** object which collects errors. From a controller, you access it directly using the **validation** variable. You can still access a subset of the API using the **play.data.validation.Validation** class’ static methods.

 

验证对象包含一个集合play.data.validation.Error对象,每一个错误有2个属性。

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

 

key,它帮助你决定哪一个数据项引发的错误,key的值可以被定义但是当Play产生错误时,它使用默认的约定,遵循Java变量的名称。

* The **key**. This helps you to determine which data element caused the error. The key value can be set arbitrarily but when Play generates errors, it uses default conventions that follow the Java variables’ names.

 

message,它包含了错误的文字描述,message可以是文本信息,或者从错误集合里(典型的是为了国际化支持)参考一个key。

* 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).

 

下面我们看一下怎样去验证一个简单的HTTP参数。

Let’s see how to validate a simple HTTP parameter:

 

bc. public static void hello(String name) {

     validation.required(name);

     ...

}

这段代码检查name变量被正确的设置了,如果不是的话,相应的信息会被增加到当前的错误集合中去。

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

 

你可以重复这个操作去验证每一个你需要的变量。

You can repeat this operation for each validation you need:

 

bc. public static void hello(String name, Integer age) {

     validation.required(name);

     validation.required(age);

     validation.min(age, 0);

     ...

}

 

重新得到错误信息

h2. <a>Retrieving error messages</a>

 

在每一个验证结束,你可以检查是否错误都被创建并显示出来了。

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

 

bc. 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());

         }

     }

}

 

假设name和age是null,那么将会显示出:

Assuming that name and age are null, this would display:

 

bc. name is required

age is required

 

默认的消息是key和message集合中key一致的,所以在conf/messages文件中你可以看到:

Default messages are keys that refer to the message bundle. So in the **conf/messages** file you will have:

 

bc. validation.required=%s is required

 

你可以改变这些默认的消息,然后再每一个项目中覆盖它,%s占位符会被错误的key所替代,你可以使用error.message(String field)方法覆盖它。

You can change this default message and override it for each application language. The **%s** placeholder will be replaced by the error key. You can override using the **error.message(String field)** method.

 

例如:

For example:

 

bc. Error error = validation.required(name).error;

if(error != null) {

    System.out.println(error.message("The name"));

}

 

你还可以为每一次检查明确指定不同的信息。

You can also specify a different message for each check:

 

bc. Error error = validation.required(name).message("Fill the name!").error;

if(error != null) {

    System.out.println(error.message());

}

 

再模板中显示错误信息

h2. <a>Displaying errors in the template</a>

 

再大多数情况下,你想让错误消息显示在视图模板中,你可以在模板中使用errors对象使用它们,一些tag帮助你显示这些错误。

In most cases you want to display the error messages in the view template. You can access them in the template using the **errors** object. Some tags help you to display the errors:

 

让我们看个例子。

Let’s see a sample:

 

bc. 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:

 

bc. #{ifErrors}

 

   <h1>Oops...</h1>

 

   #{errors}

       <li>${error}</li>

   #{/errors}

 

#{/ifErrors}

#{else}

 

   Hello ${name}, you are ${age}.

 

#{/else}

 

但是在实际的应用中,你想显示原先的form表单。所以你将有2个action,显示form表单,还要处理POST。

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

 

当然如果有错误发生的话你需要重新跳转到第一个action,但是验证会发生在第二个action中,这样你需要一些小技巧在跳转之前保持错误信息。使用validate.keey()方法,它可以为下个action保存错误集合。

Of course the validation will occur in the second action and if some error occurs you will have to redirect to the first action. In this case you need a special trick to keep your errors during the redirect. Use the **validation.keep()** method. This will save the errors collection for the next action.

 

让我们看一个真实的例子。

Let’s see a real sample:

 

bc. 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:

 

bc. #{ifErrors}

   <h1>Oops...</h1>

 

   #{errors}

       <li>${error}</li>

   #{/errors}

#{/ifErrors}

 

#{form @Application.hello()}

   <div>

      Name: <input type="text" name="name" value="${flash.name}" />

   </div>

   <div>

      Age: <input type="text" name="age" value="${flash.age}" /> 

   </div>

   <div>

      <input type="submit" value="Say hello" /> 

   </div>

#{/form}

 

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

 

bc. #{ifErrors}

   <h1>Oops...</h1>

#{/ifErrors}

 

#{form @Application.hello()}

   <div>

      Name: <input type="text" name="name" value="${flash.name}" />

      <span class="error">#{error 'name' /}</span>

   </div>

   <div>

      Age: <input type="text" name="age" value="${flash.age}" /> 

      <span class="error">#{error 'age' /}</span>

   </div>

   <div>

      <input type="submit" value="Say hello" /> 

   </div>

#{/form}

 

 

使用注解

h2. <a>Using annotations</a>

 

你可以使用注解做相同的事。

You can use annotations to do the same thing:

 

bc. 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);

}

 

验证对象

h2. <a>Validating objects</a>

 

使用注解你可以轻松的为你的model对象增加约束,让我们重写前一个例子,使用User类。

Using annotations you can easily add constraints to your model objects. Let’s rewrite the previous example using a User class.

 

First the **User** class:

 

bc. package models;

 

public class User {

 

    @Required

    public String name;

 

    @Required

    @Min(0)

    public Integer age;

 

}

 

然后修改hello action.

Then the modified **hello** action:

 

bc. 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);

}

 

最后增加一个修改后的form表单

And finally the modified form:

 

bc. #{ifErrors}

   <h1>Oops...</h1>

#{/ifErrors}

 

#{form @Application.hello()}

   <div>

      Name: <input type="text" name="user.name" value="${flash['user.name']}" />

      <span class="error">#{error 'user.name' /}</span>

   </div>

   <div>

      Age: <input type="text" name="user.age" value="${flash['user.age']}" /> 

      <span class="error">#{error 'user.age' /}</span>

   </div>

   <div>

      <input type="submit" value="Say hello" /> 

   </div>

#{/form}

 

自定义验证

h2. <a>Custom validation</a>

 

如果在play.data.validation没有发现你需要的验证,你可以自己写。然后使用@CheckWith注解绑定到你自己的Check实现里去。

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:

 

bc. public class User {

 

    @Required

    @CheckWith(MyPasswordCheck.class)

    public String password;

 

    static class MyPasswordCheck extends Check {

 

        public abstract boolean isSatisfied(Object user, Object password) {

            return notMatchPreviousPasswords(password);

        }

 

    }

}

加载中
0
迷失的鱼
迷失的鱼

不错哦!可以借鉴参考!

返回顶部
顶部