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.

79 lines
2.2 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
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. "reflect"
  7. "github.com/Unknwon/macaron"
  8. "github.com/macaron-contrib/i18n"
  9. "github.com/gogits/gogs/modules/auth"
  10. "github.com/gogits/gogs/modules/log"
  11. "github.com/gogits/gogs/modules/middleware/binding"
  12. )
  13. type MarkdownForm struct {
  14. Text string `form:"text" binding:"Required"`
  15. Mode string `form:"mode"`
  16. Context string `form:"context"`
  17. }
  18. func (f *MarkdownForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
  19. validateApiReq(errs, ctx.Data, f, l)
  20. }
  21. func validateApiReq(errs *binding.Errors, data map[string]interface{}, f interface{}, l i18n.Locale) {
  22. if errs.Count() == 0 {
  23. return
  24. } else if len(errs.Overall) > 0 {
  25. for _, err := range errs.Overall {
  26. log.Error(4, "%s: %v", reflect.TypeOf(f), err)
  27. }
  28. return
  29. }
  30. data["HasError"] = true
  31. typ := reflect.TypeOf(f)
  32. val := reflect.ValueOf(f)
  33. if typ.Kind() == reflect.Ptr {
  34. typ = typ.Elem()
  35. val = val.Elem()
  36. }
  37. for i := 0; i < typ.NumField(); i++ {
  38. field := typ.Field(i)
  39. fieldName := field.Tag.Get("form")
  40. // Allow ignored fields in the struct
  41. if fieldName == "-" {
  42. continue
  43. }
  44. if err, ok := errs.Fields[field.Name]; ok {
  45. switch err {
  46. case binding.BindingRequireError:
  47. data["ErrorMsg"] = fieldName + " cannot be empty"
  48. case binding.BindingAlphaDashError:
  49. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) characters"
  50. case binding.BindingAlphaDashDotError:
  51. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) or dot characters"
  52. case binding.BindingMinSizeError:
  53. data["ErrorMsg"] = fieldName + " must contain at least " + auth.GetMinSize(field) + " characters"
  54. case binding.BindingMaxSizeError:
  55. data["ErrorMsg"] = fieldName + " must contain at most " + auth.GetMaxSize(field) + " characters"
  56. case binding.BindingEmailError:
  57. data["ErrorMsg"] = fieldName + " is not a valid e-mail address"
  58. case binding.BindingUrlError:
  59. data["ErrorMsg"] = fieldName + " is not a valid URL"
  60. default:
  61. data["ErrorMsg"] = "Unknown error: " + err
  62. }
  63. return
  64. }
  65. }
  66. }