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.

73 lines
2.0 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
  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/binding"
  9. "github.com/gogits/gogs/modules/auth"
  10. )
  11. type MarkdownForm struct {
  12. Text string `form:"text" binding:"Required"`
  13. Mode string `form:"mode"`
  14. Context string `form:"context"`
  15. }
  16. func (f *MarkdownForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
  17. return validateApiReq(errs, ctx.Data, f)
  18. }
  19. func validateApiReq(errs binding.Errors, data map[string]interface{}, f auth.Form) binding.Errors {
  20. if errs.Len() == 0 {
  21. return errs
  22. }
  23. data["HasError"] = true
  24. typ := reflect.TypeOf(f)
  25. val := reflect.ValueOf(f)
  26. if typ.Kind() == reflect.Ptr {
  27. typ = typ.Elem()
  28. val = val.Elem()
  29. }
  30. for i := 0; i < typ.NumField(); i++ {
  31. field := typ.Field(i)
  32. fieldName := field.Tag.Get("form")
  33. // Allow ignored fields in the struct
  34. if fieldName == "-" {
  35. continue
  36. }
  37. if errs[0].FieldNames[0] == field.Name {
  38. switch errs[0].Classification {
  39. case binding.RequiredError:
  40. data["ErrorMsg"] = fieldName + " cannot be empty"
  41. case binding.AlphaDashError:
  42. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) characters"
  43. case binding.AlphaDashDotError:
  44. data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) or dot characters"
  45. case binding.MinSizeError:
  46. data["ErrorMsg"] = fieldName + " must contain at least " + auth.GetMinSize(field) + " characters"
  47. case binding.MaxSizeError:
  48. data["ErrorMsg"] = fieldName + " must contain at most " + auth.GetMaxSize(field) + " characters"
  49. case binding.EmailError:
  50. data["ErrorMsg"] = fieldName + " is not a valid e-mail address"
  51. case binding.UrlError:
  52. data["ErrorMsg"] = fieldName + " is not a valid URL"
  53. default:
  54. data["ErrorMsg"] = "Unknown error: " + errs[0].Classification
  55. }
  56. return errs
  57. }
  58. }
  59. return errs
  60. }