github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/validation/regex_pattern_test.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package validation 7 8 import ( 9 "regexp" 10 "testing" 11 12 "gitea.com/go-chi/binding" 13 ) 14 15 func getRegexPatternErrorString(pattern string) string { 16 if _, err := regexp.Compile(pattern); err != nil { 17 return err.Error() 18 } 19 return "" 20 } 21 22 var regexValidationTestCases = []validationTestCase{ 23 { 24 description: "Empty regex pattern", 25 data: TestForm{ 26 RegexPattern: "", 27 }, 28 expectedErrors: binding.Errors{}, 29 }, 30 { 31 description: "Valid regex", 32 data: TestForm{ 33 RegexPattern: `(\d{1,3})+`, 34 }, 35 expectedErrors: binding.Errors{}, 36 }, 37 38 { 39 description: "Invalid regex", 40 data: TestForm{ 41 RegexPattern: "[a-", 42 }, 43 expectedErrors: binding.Errors{ 44 binding.Error{ 45 FieldNames: []string{"RegexPattern"}, 46 Classification: ErrRegexPattern, 47 Message: getRegexPatternErrorString("[a-"), 48 }, 49 }, 50 }, 51 } 52 53 func Test_RegexPatternValidation(t *testing.T) { 54 AddBindingRules() 55 56 for _, testCase := range regexValidationTestCases { 57 t.Run(testCase.description, func(t *testing.T) { 58 performValidationTest(t, testCase) 59 }) 60 } 61 }