在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Revel提供内建的函数来验证参数.这里有一对部件:
更深入的了解验证可以看一下 示例demo 内联错误信息这个示例演示用内联错误信息验证字段. func (c MyApp) SaveUser(username string) rev.Result { // Username (required) must be between 4 and 15 letters (inclusive). c.Validation.Required(username) c.Validation.MaxSize(username, 15) c.Validation.MinSize(username, 4) c.Validation.Match(username, regexp.MustCompile("^\\w*$")) if c.Validation.HasErrors() { // Store the validation errors in the flash context and redirect. c.Validation.Keep() c.FlashParams() return c.Redirect(Hotels.Settings) } // All the data checked out! ... } 一步一步的:
Hotels.Settings aciton渲染一个模板: {{/* app/views/Hotels/Settings.html */}} ... {{if .errors}}Please fix errors marked below!{{end}} ... <p class="{{if .errors.username}}error{{end}}"> Username: <input name="username" value="{{.flash.username}}"/> <span class="error">{{.errors.username.Message}}</span> </p> 它做了3件事:
注意:字段模板帮助函数让使用验证错误框架写模板更方便一些. 顶部错误信息如果错误信息被收集到一个地方,模板可以被简化(例如, 一个大的红色红框在页面的最上面) 这里和之前的示例只有两个不同
下面是代码: func (c MyApp) SaveUser(username string) rev.Result { // Username (required) must be between 4 and 15 letters (inclusive). c.Validation.Required(username).Message("Please enter a username") c.Validation.MaxSize(username, 15).Message("Username must be at most 15 characters long") c.Validation.MinSize(username, 4).Message("Username must be at least 4 characters long") c.Validation.Match(username, regexp.MustCompile("^\\w*$")).Message("Username must be all letters") if c.Validation.HasErrors() { // Store the validation errors in the flash context and redirect. c.Validation.Keep() c.FlashParams() return c.Redirect(Hotels.Settings) } // All the data checked out! ... } 模板: {{/* app/views/Hotels/Settings.html */}} ... {{if .errors}} <div class="error> <ul> {{range .errors}} <li> {{.Message}} {{end}} </ul> </div> {{end}} ...
至此结束. |
请发表评论