在revel框架中需通过validation上下文添加正则规则(如match方法,正则省略$)和自定义校验(闭包或结构体validate方法),并配合模板错误渲染及keep/flashparams保留状态。

在Revel框架中为表单字段添加正则规则与自定义校验逻辑,需直接操作Validation上下文并配合模板错误渲染,避免仅依赖前端验证导致数据绕过。
添加正则匹配规则
调用c.Validation.Match()方法传入字段值与正则对象,Revel会自动将失败结果存入验证上下文,key默认为字段名。
例如验证用户名只含字母数字下划线:c.Validation.Match(username, regexp.MustCompile("^\w*$"))。注意正则必须用regexp.MustCompile预编译,否则运行时 panic。
这一步不能写成^\w+$——末尾的$会被Revel内部截断逻辑误判,实际应省略。
编写自定义校验函数
方法一:内联闭包校验
在控制器方法中直接写匿名函数,适用于单次、轻量逻辑。例如检查邮箱域名是否允许:
c.Validation.Add("email", func(v interface{}) string { email := v.(string) if strings.HasSuffix(email, "@example.com") { return "不允许使用 example.com 邮箱" } return ""})
方法二:复用型校验器封装
新建app/validation/UniqueUserValidator.go,定义结构体并实现Validate方法:
type UniqueUserValidator struct{}func (v *UniqueUserValidator) Validate(val interface{}) string { username := val.(string) if models.UserExists(username) { <strong>【数据库查询必须加超时控制,否则阻塞整个请求】</strong> return "用户名已被注册" } return ""}
然后在控制器中调用:c.Validation.Add("username", &UniqueUserValidator{})。
模板中显示验证错误
第一步:在模板顶部判断是否有错误
{{if .errors}}<div class="alert alert-danger">请修正以下错误:</div>{{end}}
第二步:为每个字段绑定错误提示
<p class="{{if .errors.username}}has-error{{end}}"></p> <label>用户名</label> <input name="username" value="{{.flash.username}}"> {{if .errors.username}}<span class="help-block">{{.errors.username.Message}}</span>{{end}}
第三步:确保重定向时保留错误和输入值
在控制器中验证失败后必须调用c.Validation.Keep()和c.FlashParams(),否则.flash.username为空,用户需重新填写全部内容。











