-
Notifications
You must be signed in to change notification settings - Fork 2
constraint.StringPattern
marrow16 edited this page Jan 21, 2023
·
4 revisions
Check that a string matches a given regexp pattern
Note: By default, this constraint is non-strict - if the value being checked is not a string, this constraint does not fail (unless the Strict field is set)
strpatt
| Field | Type | Description |
|---|---|---|
Regexp |
regexp.Regexp | the regexp pattern that the string value must match |
Message |
string | the violation message to be used if the constraint fails. If empty, the default message is used |
Stop |
bool | when set to true, Stop prevents further validation checks on the property if this constraint fails |
Strict |
bool | when set to true, fails if the value being checked is not a correct type |
Programmatic example...
package main
import (
"fmt"
"regexp"
"github.com/marrow16/valix"
)
func main() {
validator := &valix.Validator{
UseNumber: true,
Properties: valix.Properties{
"foo": {
Type: valix.JsonString,
Constraints: valix.Constraints{
&valix.StringPattern{
Regexp: *regexp.MustCompile(`^[a-z_][a-z]*(?:[A-Z][a-z0-9]+)*[a-z0-9_]?$`),
Message: "String value must be camel case",
},
},
},
},
}
ok, violations, _ := validator.ValidateString(`{"foo": "AtestAtest"}`)
fmt.Printf("Passed? %v\n", ok)
for i, v := range violations {
fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", i+1, v.Message, v.Property, v.Path)
}
ok, violations, _ = validator.ValidateString(`{"foo": "aTestaTest"}`)
fmt.Printf("Passed? %v\n", ok)
for i, v := range violations {
fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", i+1, v.Message, v.Property, v.Path)
}
}Struct v8n tag example...
package main
import (
"fmt"
"github.com/marrow16/valix"
)
type MyStruct struct {
Foo string `json:"foo" v8n:"&strpatt{regexp:'^[a-z_][a-z]*(?:[A-Z][a-z0-9]+)*[a-z0-9_]?$', message:'String value must be camel case'}"`
}
var validator = valix.MustCompileValidatorFor(MyStruct{}, nil)
func main() {
my := &MyStruct{}
ok, violations, _ := validator.ValidateStringInto(`{"foo": "AtestAtest"}`, my)
fmt.Printf("Passed? %v\n", ok)
for i, v := range violations {
fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", i+1, v.Message, v.Property, v.Path)
}
ok, violations, _ = validator.ValidateStringInto(`{"foo": "aTestaTest"}`, my)
fmt.Printf("Passed? %v\n", ok)
for i, v := range violations {
fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", i+1, v.Message, v.Property, v.Path)
}
}