validator.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2021 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package validator // import "miniflux.app/validator"
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "regexp"
  10. "miniflux.app/locale"
  11. )
  12. // ValidationError represents a validation error.
  13. type ValidationError struct {
  14. TranslationKey string
  15. }
  16. // NewValidationError initializes a validation error.
  17. func NewValidationError(translationKey string) *ValidationError {
  18. return &ValidationError{TranslationKey: translationKey}
  19. }
  20. func (v *ValidationError) String() string {
  21. return locale.NewPrinter("en_US").Printf(v.TranslationKey)
  22. }
  23. func (v *ValidationError) Error() error {
  24. return errors.New(v.String())
  25. }
  26. // ValidateRange makes sure the offset/limit values are valid.
  27. func ValidateRange(offset, limit int) error {
  28. if offset < 0 {
  29. return fmt.Errorf(`Offset value should be >= 0`)
  30. }
  31. if limit < 0 {
  32. return fmt.Errorf(`Limit value should be >= 0`)
  33. }
  34. return nil
  35. }
  36. // ValidateDirection makes sure the sorting direction is valid.
  37. func ValidateDirection(direction string) error {
  38. switch direction {
  39. case "asc", "desc":
  40. return nil
  41. }
  42. return fmt.Errorf(`Invalid direction, valid direction values are: "asc" or "desc"`)
  43. }
  44. // IsValidRegex verifies if the regex can be compiled.
  45. func IsValidRegex(expr string) bool {
  46. _, err := regexp.Compile(expr)
  47. return err == nil
  48. }
  49. // IsValidURL verifies if the provided value is a valid absolute URL.
  50. func IsValidURL(absoluteURL string) bool {
  51. _, err := url.ParseRequestURI(absoluteURL)
  52. return err == nil
  53. }