Пример #1
0
func (f *Form) renderField(buf *bytes.Buffer, field *Field) (err error) {
	if provider, ok := field.sval.Addr().Interface().(AddOnProvider); ok {
		field.addons = provider.FieldAddOns(f.ctx, field)
	}
	r := f.renderer
	if r != nil {
		err = r.BeginField(buf, field)
		if err != nil {
			return
		}
	}
	err = f.writeField(buf, field)
	if err != nil {
		return
	}
	if r != nil {
		if ferr := field.Err(); ferr != nil {
			ferr = i18n.TranslatedError(ferr, f.ctx)
			err = r.WriteError(buf, field, ferr)
			if err != nil {
				return
			}
		}
		if field.Help != "" {
			err = r.WriteHelp(buf, field, field.Help.TranslatedString(f.ctx))
			if err != nil {
				return
			}
		}
		err = r.EndField(buf, field)
		if err != nil {
			return
		}
	}
	return
}
Пример #2
0
func (f *Form) validate() {
	if err := f.addCSRF(); err != nil {
		panic(err)
	}
	for _, v := range f.fields {
		inp := f.ctx.FormValue(v.HTMLName)
		label := v.Label.TranslatedString(f.ctx)
		if f.NamelessErrors {
			label = ""
		}
		if v.Type.HasChoices() {
			if inp == NotChosen {
				v.err = i18n.Errorfc("form", "You must choose a value").Err(f.ctx)
				continue
			}
			// Verify that the input mathces one of the available choices
			choices := f.fieldChoices(v)
			found := false
			for _, c := range choices {
				if inp == toHTMLValue(c.Value) {
					found = true
					break
				}
			}
			if !found {
				v.err = i18n.Errorfc("form", "%v is not a valid choice", inp).Err(f.ctx)
				continue
			}
		}
		if v.Type == FILE {
			file, header, err := f.ctx.R.FormFile(v.HTMLName)
			if err != nil && !v.Tag().Optional() {
				v.err = input.RequiredInputError(label)
				continue
			}
			if file != nil && header != nil {
				value := &formFile{
					file:   file,
					header: header,
				}
				v.value.Set(reflect.ValueOf(value))
			}
		} else {
			if err := input.InputNamed(label, inp, v.SettableValue(), v.Tag(), true); err != nil {
				v.err = i18n.TranslatedError(err, f.ctx)
				continue
			}
			if v.Type == EMAIL && !v.Tag().Has("novalidate") {
				// Don't validate empty emails. If we reached this point
				// with an empty one, the field is optional.
				if email, ok := v.Value().(string); ok && email != "" {
					if _, err := mail.Validate(email, true); err != nil {
						v.err = i18n.Errorfc("form", "%q is not a valid email address", email).Err(f.ctx)
						continue
					}
				}
			}
		}
		if err := structs.Validate(v.sval.Addr().Interface(), v.Name, f.ctx); err != nil {
			v.err = i18n.TranslatedError(err, f.ctx)
			continue
		}
	}
}