-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
1,048 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
name: Test build | ||
|
||
on: | ||
pull_request: | ||
branches: | ||
- main | ||
|
||
jobs: | ||
main: | ||
name: Build and run | ||
runs-on: ubuntu-20.04 | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v3 | ||
|
||
- name: Run tests | ||
run: | | ||
go test | ||
- name: Check if binary builds | ||
run: | | ||
go build . | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,21 @@ | ||
BSD 2-Clause License | ||
MIT License | ||
|
||
Copyright (c) 2024, Go Phings | ||
Copyright (c) 2023, 2024 Mikolaj Gasior | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are met: | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
1. Redistributions of source code must retain the above copyright notice, this | ||
list of conditions and the following disclaimer. | ||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
2. Redistributions in binary form must reproduce the above copyright notice, | ||
this list of conditions and the following disclaimer in the documentation | ||
and/or other materials provided with the distribution. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,38 @@ | ||
# struct-validator | ||
Verify the values of struct fields using tags | ||
|
||
[![Go Reference](https://pkg.go.dev/badge/github.com/go-phings/struct-validator.svg)](https://pkg.go.dev/github.com/go-phings/struct-validator) [![Go Report Card](https://goreportcard.com/badge/github.com/go-phings/struct-validator)](https://goreportcard.com/report/github.com/go-phings/struct-validator) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/go-phings/struct-validator?sort=semver) | ||
|
||
Verify the values of struct fields using tags | ||
|
||
### Example code | ||
|
||
``` | ||
type Test1 struct { | ||
FirstName string `validation:"req lenmin:5 lenmax:25"` | ||
LastName string `validation:"req lenmin:2 lenmax:50"` | ||
Age int `validation:"req valmin:18 valmax:150"` | ||
Price int `validation:"req valmin:0 valmax:9999"` | ||
PostCode string `validation:"req" validation_regexp:"^[0-9][0-9]-[0-9][0-9][0-9]$"` | ||
Email string `validation:"req email"` | ||
BelowZero int `validation:"valmin:-6 valmax:-2"` | ||
DiscountPrice int `validation:"valmin:0 valmax:8000"` | ||
Country string `validation_regexp:"^[A-Z][A-Z]$"` | ||
County string `validation:"lenmax:40"` | ||
} | ||
s := &Test1{ | ||
FirstName: "Name that is way too long and certainly not valid", | ||
... | ||
} | ||
o := structvalidator.&ValidationOptions{ | ||
RestrictFields: map[string]bool{ | ||
"FirstName": true, | ||
"LastName": true, | ||
... | ||
}, | ||
... | ||
} | ||
isValid, fieldsWithInvalidValue := structvalidator.Validate(s, &o) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
module github.com/go-phings/struct-validator | ||
|
||
go 1.23.4 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
package structvalidator | ||
|
||
import ( | ||
"fmt" | ||
"html" | ||
"reflect" | ||
"strconv" | ||
"strings" | ||
) | ||
|
||
const TypeText = 1 | ||
const TypeTextarea = 2 | ||
const TypePassword = 3 | ||
const TypeEmail = 4 | ||
|
||
// Optional configuration for validation: | ||
// * RestrictFields defines what struct fields should be generated | ||
// * ExcludeFields defines fields that should be skipped (also from RestrictFields) | ||
// * OverwriteFieldTags can be used to overwrite tags for specific fields | ||
// * OverwriteTagName sets tag used to define validation (default is "validation") | ||
// * ValidateWhenSuffix will validate certain fields based on their name, eg. "PrimaryEmail" field will need to be a valid email | ||
// * OverwriteFieldValues is to use overwrite values for fields, so these values are validated not the ones in struct | ||
// * IDPrefix - if added, an element will contain an 'id' attribute in form of prefix + field name | ||
// * NamePrefix - use this to put a prefix in the 'name' attribute | ||
// * OverwriteValues - fill inputs with the specified values | ||
// * FieldValues - when true then fill inputs with struct instance values | ||
type HTMLOptions struct { | ||
RestrictFields map[string]bool | ||
ExcludeFields map[string]bool | ||
OverwriteFieldTags map[string]map[string]string | ||
OverwriteTagName string | ||
ValidateWhenSuffix bool | ||
IDPrefix string | ||
NamePrefix string | ||
OverwriteValues map[string]string | ||
FieldValues bool | ||
} | ||
|
||
// GenerateHTMLInput takes a struct and generates HTML inputs for each of the fields, eg. <input> or <textarea> | ||
func GenerateHTML(obj interface{}, options *HTMLOptions) map[string]string { | ||
v := reflect.ValueOf(obj) | ||
i := reflect.Indirect(v) | ||
s := i.Type() | ||
elem := v.Elem() | ||
|
||
tagName := "validation" | ||
if options != nil && options.OverwriteTagName != "" { | ||
tagName = options.OverwriteTagName | ||
} | ||
|
||
fields := map[string]string{} | ||
|
||
for j := 0; j < s.NumField(); j++ { | ||
field := s.Field(j) | ||
fieldKind := field.Type.Kind() | ||
|
||
// check if only specified field should be checked | ||
if options != nil && len(options.RestrictFields) > 0 && !options.RestrictFields[field.Name] { | ||
continue | ||
} | ||
|
||
// check if field should not be excluded | ||
if options != nil && len(options.ExcludeFields) > 0 && options.ExcludeFields[field.Name] { | ||
continue | ||
} | ||
|
||
// generate only ints, string and bool | ||
if !isInt(fieldKind) && !isString(fieldKind) && !isBool(fieldKind) { | ||
continue | ||
} | ||
|
||
// value | ||
value := "" | ||
|
||
if options != nil && options.FieldValues { | ||
if isBool(fieldKind) && elem.Field(j).Bool() { | ||
value = "true" | ||
} | ||
if isString(fieldKind) { | ||
value = elem.Field(j).String() | ||
} | ||
if isInt(fieldKind) { | ||
value = fmt.Sprintf("%d", elem.Field(j).Int()) | ||
} | ||
} | ||
|
||
if options != nil && len(options.OverwriteValues) > 0 && options.OverwriteValues[field.Name] != "" { | ||
value = options.OverwriteValues[field.Name] | ||
} | ||
|
||
// 'id' attribute | ||
fieldIDAttr := "" | ||
if options.IDPrefix != "" { | ||
fieldIDAttr = fmt.Sprintf(` id="%s%s"`, options.IDPrefix, field.Name) | ||
} | ||
fieldNameAttr := fmt.Sprintf(` name="%s%s"`, options.NamePrefix, field.Name) | ||
|
||
if isBool(fieldKind) { | ||
fieldChecked := "" | ||
if value == "true" { | ||
fieldChecked = " checked" | ||
} | ||
|
||
fields[field.Name] = fmt.Sprintf(`<input type="checkbox"%s%s%s>`, fieldNameAttr, fieldIDAttr, fieldChecked) | ||
continue | ||
} | ||
|
||
// get tag values | ||
tagVal := field.Tag.Get(tagName) | ||
tagRegexpVal := field.Tag.Get(tagName + "_regexp") | ||
if options != nil && len(options.OverwriteFieldTags) > 0 { | ||
if len(options.OverwriteFieldTags[field.Name]) > 0 { | ||
if options.OverwriteFieldTags[field.Name][tagName] != "" { | ||
tagVal = options.OverwriteFieldTags[field.Name][tagName] | ||
} | ||
if options.OverwriteFieldTags[field.Name][tagName+"_regexp"] != "" { | ||
tagRegexpVal = options.OverwriteFieldTags[field.Name][tagName+"_regexp"] | ||
} | ||
} | ||
} | ||
|
||
patternAttr := "" | ||
if tagRegexpVal != "" { | ||
patternAttr = fmt.Sprintf(` pattern="%s"`, html.EscapeString(tagRegexpVal)) | ||
} | ||
validationAttrs, inputType := getHTMLAttributesFromTag(tagVal) | ||
|
||
if options != nil && options.ValidateWhenSuffix { | ||
if strings.HasSuffix(field.Name, "Email") { | ||
inputType = TypeEmail | ||
} | ||
// Price not supported here yet | ||
} | ||
|
||
fieldValue := "" | ||
if value != "" { | ||
fieldValue = fmt.Sprintf(" value=\"%s\"", html.EscapeString(value)) | ||
} | ||
|
||
if isInt(fieldKind) { | ||
fields[field.Name] = fmt.Sprintf(`<input type="number"%s%s%s%s/>`, fieldNameAttr, fieldIDAttr, validationAttrs, fieldValue) | ||
continue | ||
} | ||
|
||
if isString(fieldKind) { | ||
if inputType == TypeTextarea { | ||
fields[field.Name] = fmt.Sprintf(`<textarea%s%s%s%s>%s</textarea>`, fieldNameAttr, fieldIDAttr, validationAttrs, patternAttr, html.EscapeString(value)) | ||
continue | ||
} | ||
fieldTypeAttr := ` type="text"` | ||
if inputType == TypeEmail { | ||
fieldTypeAttr = ` type="email"` | ||
} | ||
if inputType == TypePassword { | ||
fieldTypeAttr = ` type="password"` | ||
fieldValue = "" | ||
} | ||
fields[field.Name] = fmt.Sprintf(`<input%s%s%s%s%s%s/>`, fieldTypeAttr, fieldNameAttr, fieldIDAttr, validationAttrs, patternAttr, fieldValue) | ||
continue | ||
} | ||
} | ||
|
||
return fields | ||
} | ||
|
||
func getHTMLAttributesFromTag(tag string) (string, int) { | ||
attrs := "" | ||
inputType := TypeText | ||
|
||
opts := strings.SplitN(tag, " ", -1) | ||
for _, opt := range opts { | ||
if opt == "req" { | ||
attrs = attrs + " required" | ||
} | ||
if opt == "email" { | ||
inputType = TypeEmail | ||
continue | ||
} | ||
if opt == "uitextarea" { | ||
inputType = TypeTextarea | ||
} | ||
if opt == "uipassword" { | ||
inputType = TypePassword | ||
} | ||
for _, valOpt := range []string{"lenmin", "lenmax", "valmin", "valmax", "regexp"} { | ||
if strings.HasPrefix(opt, valOpt+":") { | ||
val := strings.Replace(opt, valOpt+":", "", 1) | ||
if valOpt == "regexp" { | ||
attrs = attrs + fmt.Sprintf(` pattern="%s"`, html.EscapeString(val)) | ||
continue | ||
} | ||
|
||
i, err := strconv.Atoi(val) | ||
if err != nil { | ||
continue | ||
} | ||
switch valOpt { | ||
case "lenmin": | ||
attrs = attrs + fmt.Sprintf(` minlength="%d"`, i) | ||
case "lenmax": | ||
attrs = attrs + fmt.Sprintf(` maxlength="%d"`, i) | ||
case "valmin": | ||
attrs = attrs + fmt.Sprintf(` min="%d"`, i) | ||
case "valmax": | ||
attrs = attrs + fmt.Sprintf(` max="%d"`, i) | ||
} | ||
} | ||
} | ||
} | ||
|
||
return attrs, inputType | ||
} |
Oops, something went wrong.