You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package apiv1
  5. import (
  6. "net/http"
  7. "reflect"
  8. "github.com/go-martini/martini"
  9. "github.com/gogits/gogs/modules/auth"
  10. "github.com/gogits/gogs/modules/base"
  11. "github.com/gogits/gogs/modules/log"
  12. "github.com/gogits/gogs/modules/middleware/binding"
  13. )
  14. type MarkdownForm struct {
  15. Text string `form:"text" binding:"Required"`
  16. Mode string `form:"mode"`
  17. Context string `form:"context"`
  18. }
  19. func (f *MarkdownForm) Validate(errs *binding.Errors, req *http.Request, ctx martini.Context) {
  20. data := ctx.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData)
  21. validateApiReq(errs, data, f)
  22. }
  23. func validateApiReq(errs *binding.Errors, data base.TmplData, f interface{}) {
  24. if errs.Count() == 0 {
  25. return
  26. } else if len(errs.Overall) > 0 {
  27. for _, err := range errs.Overall {
  28. log.Error("%s: %v", reflect.TypeOf(f), err)
  29. }
  30. return
  31. }
  32. data["HasError"] = true
  33. typ := reflect.TypeOf(f)
  34. val := reflect.ValueOf(f)
  35. if typ.Kind() == reflect.Ptr {
  36. typ = typ.Elem()
  37. val = val.Elem()
  38. }
  39. for i := 0; i < typ.NumField(); i++ {
  40. field := typ.Field(i)
  41. fieldName := field.Tag.Get("form")
  42. // Allow ignored fields in the struct
  43. if fieldName == "-" {
  44. continue
  45. }
  46. if err, ok := errs.Fields[field.Name]; ok {
  47. switch err {
  48. case binding.BindingRequireError:
  49. data["ErrorMsg"] = fieldName + " cannot be empty"
  50. case binding.BindingAlphaDashError:
  51. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) characters"
  52. case binding.BindingAlphaDashDotError:
  53. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) or dot characters"
  54. case binding.BindingMinSizeError:
  55. data["ErrorMsg"] = fieldName + " must contain at least " + auth.GetMinMaxSize(field) + " characters"
  56. case binding.BindingMaxSizeError:
  57. data["ErrorMsg"] = fieldName + " must contain at most " + auth.GetMinMaxSize(field) + " characters"
  58. case binding.BindingEmailError:
  59. data["ErrorMsg"] = fieldName + " is not a valid e-mail address"
  60. case binding.BindingUrlError:
  61. data["ErrorMsg"] = fieldName + " is not a valid URL"
  62. default:
  63. data["ErrorMsg"] = "Unknown error: " + err
  64. }
  65. return
  66. }
  67. }
  68. }