Xitrum学习笔记13

Xitrum包含 jQuery Validation plugin用来在客户端做验证在服务器端提供验证辅助。

关于jQuery Validation plugin,参考http://bassistance.de/jquery-plugins/jquery-plugin-validation/

默认验证器

Xitrum提供的验证器在 xitrum.validator包中,有以下方法:

check(value): Boolean
message(name, value): Option[String]
exception(name, value)

如果验证没有通过,message会返回Some(error message),exception会抛出xitrum.exception.InvalidInput(error message)

可以在任何地方使用验证器

Action示例:

import xitrum.validator.Required
@POST("articles")
class CreateArticle {
  def execute() {
    val title = param("tite")
    val body = param("body")
    Required.exception("Title", title)
    Required.exception("Body", body)
    // Do with the valid title and body...
  }
}

如果不使用try和catch,当验证检查没有通过,Xitrum会自动捕获异常,并将错误信息响应给请求的客户端。

这对写web APIs或客户端已经实现了验证的情况下非常方便。

Model示例:

import xitrum.validator.Required
case class Article(id: Int = 0, title: String = "", body: String = "") {
  def isValid = Required.check(title) && Required.check(body)

  def validationMessage = Required.message(title) orElse Required.message(body)
}

xitrum.validator包中包括了所有的默认验证器

自定义验证器

扩展xitrum.validator.Validator,实现check和message方法。

也可以是Apache的Commons Validator,参照http://commons.apache.org/proper/commons-validator/

原文地址:https://www.cnblogs.com/sunspeedzy/p/6861170.html