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 5package validator // import "miniflux.app/validator" 6 7import ( 8 "errors" 9 "fmt" 10 "net/url" 11 "regexp" 12 13 "miniflux.app/locale" 14) 15 16// ValidationError represents a validation error. 17type ValidationError struct { 18 TranslationKey string 19} 20 21// NewValidationError initializes a validation error. 22func NewValidationError(translationKey string) *ValidationError { 23 return &ValidationError{TranslationKey: translationKey} 24} 25 26func (v *ValidationError) String() string { 27 return locale.NewPrinter("en_US").Printf(v.TranslationKey) 28} 29 30func (v *ValidationError) Error() error { 31 return errors.New(v.String()) 32} 33 34// ValidateRange makes sure the offset/limit values are valid. 35func ValidateRange(offset, limit int) error { 36 if offset < 0 { 37 return fmt.Errorf(`Offset value should be >= 0`) 38 } 39 40 if limit < 0 { 41 return fmt.Errorf(`Limit value should be >= 0`) 42 } 43 44 return nil 45} 46 47// ValidateDirection makes sure the sorting direction is valid. 48func ValidateDirection(direction string) error { 49 switch direction { 50 case "asc", "desc": 51 return nil 52 } 53 54 return fmt.Errorf(`Invalid direction, valid direction values are: "asc" or "desc"`) 55} 56 57// IsValidRegex verifies if the regex can be compiled. 58func IsValidRegex(expr string) bool { 59 _, err := regexp.Compile(expr) 60 return err == nil 61} 62 63// IsValidURL verifies if the provided value is a valid absolute URL. 64func IsValidURL(absoluteURL string) bool { 65 _, err := url.ParseRequestURI(absoluteURL) 66 return err == nil 67} 68