validators.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Copyright 2011 The Walk Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build windows
  5. package walk
  6. import (
  7. "errors"
  8. "fmt"
  9. "regexp"
  10. )
  11. type Validator interface {
  12. Validate(v interface{}) error
  13. }
  14. type RangeValidator struct {
  15. min float64
  16. max float64
  17. }
  18. func NewRangeValidator(min, max float64) (*RangeValidator, error) {
  19. if max <= min {
  20. return nil, errors.New("max <= min")
  21. }
  22. return &RangeValidator{min: min, max: max}, nil
  23. }
  24. func (rv *RangeValidator) Min() float64 {
  25. return rv.min
  26. }
  27. func (rv *RangeValidator) Max() float64 {
  28. return rv.max
  29. }
  30. func (rv *RangeValidator) Validate(v interface{}) error {
  31. f64 := v.(float64)
  32. if f64 < rv.min || f64 > rv.max {
  33. return errors.New(tr("The number is out of the allowed range.", "walk"))
  34. }
  35. return nil
  36. }
  37. type RegexpValidator struct {
  38. re *regexp.Regexp
  39. }
  40. func NewRegexpValidator(pattern string) (*RegexpValidator, error) {
  41. re, err := regexp.Compile(pattern)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &RegexpValidator{re}, nil
  46. }
  47. func (rv *RegexpValidator) Pattern() string {
  48. return rv.re.String()
  49. }
  50. func (rv *RegexpValidator) Validate(v interface{}) error {
  51. var matched bool
  52. switch val := v.(type) {
  53. case string:
  54. matched = rv.re.MatchString(val)
  55. case []byte:
  56. matched = rv.re.Match(val)
  57. case fmt.Stringer:
  58. matched = rv.re.MatchString(val.String())
  59. default:
  60. panic("Unsupported type")
  61. }
  62. if !matched {
  63. return errors.New(tr("The text does not match the required pattern.", "walk"))
  64. }
  65. return nil
  66. }
  67. type selectionRequiredValidator struct {
  68. }
  69. var selectionRequiredValidatorSingleton Validator = selectionRequiredValidator{}
  70. func SelectionRequiredValidator() Validator {
  71. return selectionRequiredValidatorSingleton
  72. }
  73. func (selectionRequiredValidator) Validate(v interface{}) error {
  74. if v == nil {
  75. // For Widgets like ComboBox nil is passed to indicate "no selection".
  76. return errors.New(tr("A selection is required.", "walk"))
  77. }
  78. return nil
  79. }