Form

管理字段校验、提交与错误反馈。

实时预览

正在加载预览…

参数配置

全部字段 6

FormOptions

Styles · 0

Go 代码

Go
// Inside a view; c is *ui.Context, t is nui.Theme.
// Keep s (example state) outside the view. See the complete example.
nui.Form(c.Key("form"), t, &s.Form, nui.FormOptions{Label: "Project form", Disabled: false, Validate: func(values nui.FormValues) nui.FormErrors {
	if strings.TrimSpace(values["name"]) == "" {
		return nui.FormErrors{"name": "Enter a project name"}
	}
	return nil
}, OnSubmit: func(values nui.FormValues) { s.Status = "Saved: " + values["name"] }}, func(t nui.Theme) {
	nui.FormField(c.Key("field"), t, nui.FormFieldOptions{Name: "name", Value: s.Name, Label: "Project name", Required: true}, func(t nui.Theme) {
		nui.Input(c.Key("name"), t, &s.Name, nui.InputOptions{Placeholder: "A new project"})
	})
	nui.Button(c.Key("submit"), t, "Save project", nui.ButtonOptions{}).OnClick(s.Form.Submit)
})
ui.Text(c, s.Status)

使用说明

先提交空表单查看必填校验,再输入项目名并保存。FormState 持久保存注册字段与提交状态,Validate 返回按字段名映射的错误,OnSubmit 处理验证后的数据。

API 参考

func Form(c *ui.Context, t Theme, s *FormState, o FormOptions, content func(Theme)) ui.Element

FormOptions

源码
type FormOptions struct {
	Label    string
	Disabled bool
	Validate FormValidator
	OnSubmit func(FormValues)
	Decoration
}
字段类型说明
Labelstring

Go 零值: ""

控件标签或可访问名称。

Disabledbool

Go 零值: false

禁用组件及其交互。

ValidateFormValidator

Go 零值: zero value

返回字段错误的表单校验函数。

OnSubmitfunc(FormValues)

Go 零值: nil

提交表单或输入时通知应用的回调。

UIStyles

Go 零值: zero value

以部件名称为键覆盖外观和间距。

Stylefunc(Slot, ui.Element)

Go 零值: nil

同步配置当前构建的部件;不要保留 Element。

FormState

源码
type FormState struct {
	Fields map[string]*FormFieldState

	Submitting bool
	// contains filtered or unexported fields
}
字段类型说明
Fieldsmap[string]*FormFieldState

Go 零值: nil

以字段名称索引的表单状态。

Submittingbool

Go 零值: false

表单是否正在提交。