May 15, 2021 Revel
Revel brings its own parameter validation:
The sample application provides some examples of in-depth understanding of parameter validation.
The following demonstrates using inline error messages to validate fields
func (c MyApp) SaveUser(username string) revel.Result {
// Username (required) 至少 4 - 15 个字符.
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() {
// 在flash上下文中保存验证错误并重定向
c.Validation.Keep()
c.FlashParams()
return c.Redirect(Hotels.Settings)
}
// All the data checked out!
...
}
username
field validation conditions (Required required, MinSize minimum length, MaxSize maximum length, Match matches a regular expression).
Validation.HasErrors()
true if validation does not pass
Validation.Keep()
Revel serialization to verify the error message into the Flash cookie.
The Hotels.Settings method renders a template:
{{/* 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>
It does three things:
errors
map
username
username
Note: The template function field uses a validation error framework to make it easier to write templates.
If the error messages are displayed in one place, the template becomes simple (for example, in a red box at the top of the page.)
The following example is two different from the one above:
Message
specified a validation error message for the field
The code is as follows:
func (c MyApp) SaveUser(username string) revel.Result {
// Username (必填) 至少 4 - 15 字符.
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() {
// 保存错误信息到 flash 上下文中并重定向
c.Validation.Keep()
c.FlashParams()
return c.Redirect(Hotels.Settings)
}
// All the data checked out!
...
}
The template is as follows:
{{/* app/views/Hotels/Settings.html */}}
...
{{if .errors}}
<div class="error">
<ul>
{{range .errors}}
<li> {{.Message}}</li>
{{end}}
</ul>
</div>
{{end}}
...