How to use Tags method of validation Package

Best Gauge code snippet using validation.Tags

certificate.go

Source:certificate.go Github

copy

Full Screen

...160 "status": {161 Type: schema.TypeString,162 Computed: true,163 },164 "tags": tftags.TagsSchema(),165 "tags_all": tftags.TagsSchemaComputed(),166 },167 CustomizeDiff: customdiff.Sequence(168 func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error {169 // Attempt to calculate the domain validation options based on domains present in domain_name and subject_alternative_names170 if diff.Get("validation_method").(string) == "DNS" && (diff.HasChange("domain_name") || diff.HasChange("subject_alternative_names")) {171 domainValidationOptionsList := []interface{}{map[string]interface{}{172 // AWS Provider 3.0 -- plan-time validation prevents "domain_name"173 // argument to accept a string with trailing period; thus, trim of trailing period174 // no longer required here175 "domain_name": diff.Get("domain_name").(string),176 }}177 if sanSet, ok := diff.Get("subject_alternative_names").(*schema.Set); ok {178 for _, sanRaw := range sanSet.List() {179 san, ok := sanRaw.(string)180 if !ok {181 continue182 }183 m := map[string]interface{}{184 // AWS Provider 3.0 -- plan-time validation prevents "subject_alternative_names"185 // argument to accept strings with trailing period; thus, trim of trailing period186 // no longer required here187 "domain_name": san,188 }189 domainValidationOptionsList = append(domainValidationOptionsList, m)190 }191 }192 if err := diff.SetNew("domain_validation_options", schema.NewSet(acmDomainValidationOptionsHash, domainValidationOptionsList)); err != nil {193 return fmt.Errorf("error setting new domain_validation_options diff: %w", err)194 }195 }196 return nil197 },198 verify.SetTagsDiff,199 ),200 }201}202func resourceCertificateCreate(d *schema.ResourceData, meta interface{}) error {203 if _, ok := d.GetOk("domain_name"); ok {204 if _, ok := d.GetOk("certificate_authority_arn"); ok {205 return resourceCertificateCreateRequested(d, meta)206 }207 if _, ok := d.GetOk("validation_method"); !ok {208 return errors.New("validation_method must be set when creating a certificate")209 }210 return resourceCertificateCreateRequested(d, meta)211 } else if _, ok := d.GetOk("private_key"); ok {212 if _, ok := d.GetOk("certificate_body"); !ok {213 return errors.New("certificate_body must be set when importing a certificate with private_key")214 }215 return resourceCertificateCreateImported(d, meta)216 }217 return errors.New("certificate must be imported (private_key) or created (domain_name)")218}219func resourceCertificateCreateImported(d *schema.ResourceData, meta interface{}) error {220 conn := meta.(*conns.AWSClient).ACMConn221 defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig222 tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))223 input := &acm.ImportCertificateInput{224 Certificate: []byte(d.Get("certificate_body").(string)),225 PrivateKey: []byte(d.Get("private_key").(string)),226 }227 if v, ok := d.GetOk("certificate_chain"); ok {228 input.CertificateChain = []byte(v.(string))229 }230 if len(tags) > 0 {231 input.Tags = Tags(tags.IgnoreAWS())232 }233 output, err := conn.ImportCertificate(input)234 if err != nil {235 return fmt.Errorf("error importing ACM Certificate: %w", err)236 }237 d.SetId(aws.StringValue(output.CertificateArn))238 return resourceCertificateRead(d, meta)239}240func resourceCertificateCreateRequested(d *schema.ResourceData, meta interface{}) error {241 conn := meta.(*conns.AWSClient).ACMConn242 defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig243 tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))244 params := &acm.RequestCertificateInput{245 DomainName: aws.String(d.Get("domain_name").(string)),246 IdempotencyToken: aws.String(resource.PrefixedUniqueId("tf")), // 32 character limit247 Options: expandAcmCertificateOptions(d.Get("options").([]interface{})),248 }249 if len(tags) > 0 {250 params.Tags = Tags(tags.IgnoreAWS())251 }252 if caARN, ok := d.GetOk("certificate_authority_arn"); ok {253 params.CertificateAuthorityArn = aws.String(caARN.(string))254 }255 if sans, ok := d.GetOk("subject_alternative_names"); ok {256 subjectAlternativeNames := make([]*string, len(sans.(*schema.Set).List()))257 for i, sanRaw := range sans.(*schema.Set).List() {258 subjectAlternativeNames[i] = aws.String(sanRaw.(string))259 }260 params.SubjectAlternativeNames = subjectAlternativeNames261 }262 if v, ok := d.GetOk("validation_method"); ok {263 params.ValidationMethod = aws.String(v.(string))264 }265 log.Printf("[DEBUG] ACM Certificate Request: %#v", params)266 resp, err := conn.RequestCertificate(params)267 if err != nil {268 return fmt.Errorf("Error requesting certificate: %s", err)269 }270 d.SetId(aws.StringValue(resp.CertificateArn))271 return resourceCertificateRead(d, meta)272}273func resourceCertificateRead(d *schema.ResourceData, meta interface{}) error {274 conn := meta.(*conns.AWSClient).ACMConn275 defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig276 ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig277 params := &acm.DescribeCertificateInput{278 CertificateArn: aws.String(d.Id()),279 }280 return resource.Retry(AcmCertificateDnsValidationAssignmentTimeout, func() *resource.RetryError {281 resp, err := conn.DescribeCertificate(params)282 if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, acm.ErrCodeResourceNotFoundException) {283 log.Printf("[WARN] ACM Certificate (%s) not found, removing from state", d.Id())284 d.SetId("")285 return nil286 }287 if err != nil {288 return resource.NonRetryableError(fmt.Errorf("error reading ACM Certificate (%s): %w", d.Id(), err))289 }290 if resp == nil || resp.Certificate == nil {291 return resource.NonRetryableError(fmt.Errorf("error reading ACM Certificate (%s): empty response", d.Id()))292 }293 if !d.IsNewResource() && aws.StringValue(resp.Certificate.Status) == acm.CertificateStatusValidationTimedOut {294 log.Printf("[WARN] ACM Certificate (%s) validation timed out, removing from state", d.Id())295 d.SetId("")296 return nil297 }298 d.Set("domain_name", resp.Certificate.DomainName)299 d.Set("arn", resp.Certificate.CertificateArn)300 d.Set("certificate_authority_arn", resp.Certificate.CertificateAuthorityArn)301 if err := d.Set("subject_alternative_names", cleanUpSubjectAlternativeNames(resp.Certificate)); err != nil {302 return resource.NonRetryableError(err)303 }304 domainValidationOptions, emailValidationOptions, err := convertValidationOptions(resp.Certificate)305 if err != nil {306 return resource.RetryableError(err)307 }308 if err := d.Set("domain_validation_options", domainValidationOptions); err != nil {309 return resource.NonRetryableError(err)310 }311 if err := d.Set("validation_emails", emailValidationOptions); err != nil {312 return resource.NonRetryableError(err)313 }314 d.Set("validation_method", resourceCertificateValidationMethod(resp.Certificate))315 if err := d.Set("options", flattenAcmCertificateOptions(resp.Certificate.Options)); err != nil {316 return resource.NonRetryableError(fmt.Errorf("error setting certificate options: %s", err))317 }318 d.Set("status", resp.Certificate.Status)319 tags, err := ListTags(conn, d.Id())320 if err != nil {321 return resource.NonRetryableError(fmt.Errorf("error listing tags for ACM Certificate (%s): %s", d.Id(), err))322 }323 tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)324 //lintignore:AWSR002325 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {326 return resource.NonRetryableError(fmt.Errorf("error setting tags: %w", err))327 }328 if err := d.Set("tags_all", tags.Map()); err != nil {329 return resource.NonRetryableError(fmt.Errorf("error setting tags_all: %w", err))330 }331 return nil332 })333}334func resourceCertificateValidationMethod(certificate *acm.CertificateDetail) string {335 if aws.StringValue(certificate.Type) == acm.CertificateTypeAmazonIssued {336 for _, domainValidation := range certificate.DomainValidationOptions {337 if domainValidation.ValidationMethod != nil {338 return aws.StringValue(domainValidation.ValidationMethod)339 }340 }341 }342 return "NONE"343}344func resourceCertificateUpdate(d *schema.ResourceData, meta interface{}) error {345 conn := meta.(*conns.AWSClient).ACMConn346 if d.HasChanges("private_key", "certificate_body", "certificate_chain") {347 // Prior to version 3.0.0 of the Terraform AWS Provider, these attributes were stored in state as hashes.348 // If the changes to these attributes are only changes only match updating the state value, then skip the API call.349 oCBRaw, nCBRaw := d.GetChange("certificate_body")350 oCCRaw, nCCRaw := d.GetChange("certificate_chain")351 oPKRaw, nPKRaw := d.GetChange("private_key")352 if !isChangeNormalizeCertRemoval(oCBRaw, nCBRaw) || !isChangeNormalizeCertRemoval(oCCRaw, nCCRaw) || !isChangeNormalizeCertRemoval(oPKRaw, nPKRaw) {353 input := &acm.ImportCertificateInput{354 Certificate: []byte(d.Get("certificate_body").(string)),355 CertificateArn: aws.String(d.Get("arn").(string)),356 PrivateKey: []byte(d.Get("private_key").(string)),357 }358 if chain, ok := d.GetOk("certificate_chain"); ok {359 input.CertificateChain = []byte(chain.(string))360 }361 _, err := conn.ImportCertificate(input)362 if err != nil {363 return fmt.Errorf("error re-importing ACM Certificate (%s): %w", d.Id(), err)364 }365 }366 }367 if d.HasChange("tags_all") {368 o, n := d.GetChange("tags_all")369 if err := UpdateTags(conn, d.Id(), o, n); err != nil {370 return fmt.Errorf("error updating tags: %s", err)371 }372 }373 return resourceCertificateRead(d, meta)374}375func cleanUpSubjectAlternativeNames(cert *acm.CertificateDetail) []string {376 sans := cert.SubjectAlternativeNames377 vs := make([]string, 0)378 for _, v := range sans {379 if aws.StringValue(v) != aws.StringValue(cert.DomainName) {380 vs = append(vs, aws.StringValue(v))381 }382 }383 return vs...

Full Screen

Full Screen

validationService.go

Source:validationService.go Github

copy

Full Screen

...19 validation.Required,20 validation.By(v.validateStringPtrRuneCount(1, 100))),21 validation.Field(&task.DateTarget,22 validation.Min(time.Now().AddDate(0, 0, -1))),23 validation.Field(&task.Tags,24 validation.Skip.When(len(task.Tags) == 0),25 validation.By(v.validateTagSlice)),26 )27}28func (v *ValidationService) ValidateTag(tag *dto.Tag) error {29 return validation.ValidateStruct(tag,30 validation.Field(&tag.Name,31 validation.Required,32 validation.By(v.validateStringRuneCount(1, 30))),33 )34}35func (v *ValidationService) ValidateFeedback(feedback *dto.Feedback) error {36 return validation.ValidateStruct(feedback,37 validation.Field(&feedback.Content,38 validation.NotNil,39 validation.Required,40 validation.By(v.validateStringPtrRuneCount(1,1000))))41}42func (v *ValidationService) validateStringPtrRuneCount(min int, max int) validation.RuleFunc {43 return func(value interface{}) error {44 stringPtr, ok := value.(*string)45 if !ok {46 return errors.New("not a string")47 }48 runeCount := len([]rune(*stringPtr))49 if runeCount > max || runeCount < min {50 return errors.New(fmt.Sprintf("the length must be between %d and %d.", min, max))51 }52 return nil53 }54}55func (v *ValidationService) validateStringRuneCount(min int, max int) validation.RuleFunc {56 return func(value interface{}) error {57 string, ok := value.(string)58 if !ok {59 return errors.New("not a string")60 }61 runeCount := len([]rune(string))62 if runeCount > max || runeCount < min {63 return errors.New(fmt.Sprintf("the length must be between %d and %d.", min, max))64 }65 return nil66 }67}68func (v *ValidationService) ValidateTags(tags []*dto.Tag) error {69 return validation.Validate(tags, validation.By(v.validateTagSlice))70}71func (v *ValidationService) validateTagSlice(value interface{}) error {72 tags, ok := value.([]*dto.Tag)73 if !ok {74 return errors.New("not a tag array")75 }76 for _, tag := range tags {77 if err := v.ValidateTag(tag); err != nil {78 return err79 }80 }81 for i := 0; i < len(tags)-1; i++ {82 for j := i + 1; j < len(tags); j++ {...

Full Screen

Full Screen

example_validatable_struct_test.go

Source:example_validatable_struct_test.go Github

copy

Full Screen

...7 "github.com/muonsoft/validation/validator"8)9type Product struct {10 Name string11 Tags []string12 Components []Component13}14func (p Product) Validate(ctx context.Context, validator *validation.Validator) error {15 return validator.Validate(16 ctx,17 validation.StringProperty("name", p.Name, it.IsNotBlank()),18 validation.CountableProperty("tags", len(p.Tags), it.HasMinCount(5)),19 validation.ComparablesProperty[string]("tags", p.Tags, it.HasUniqueValues[string]()),20 validation.EachStringProperty("tags", p.Tags, it.IsNotBlank()),21 validation.CountableProperty("components", len(p.Components), it.HasMinCount(1)),22 // this runs validation on each of the components23 validation.ValidSliceProperty("components", p.Components),24 )25}26type Component struct {27 ID int28 Name string29 Tags []string30}31func (c Component) Validate(ctx context.Context, validator *validation.Validator) error {32 return validator.Validate(33 ctx,34 validation.StringProperty("name", c.Name, it.IsNotBlank()),35 validation.CountableProperty("tags", len(c.Tags), it.HasMinCount(1)),36 )37}38func ExampleValid_validatableStruct() {39 p := Product{40 Name: "",41 Tags: []string{"device", "", "phone", "device"},42 Components: []Component{43 {44 ID: 1,45 Name: "",46 },47 },48 }49 err := validator.Validate(context.Background(), validation.Valid(p))50 if violations, ok := validation.UnwrapViolationList(err); ok {51 for violation := violations.First(); violation != nil; violation = violation.Next() {52 fmt.Println(violation)53 }54 }55 // Output:...

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func main() {5 validate := validator.New()6 u := User{

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 validate := validator.New()6 person := Person{Name: "Bob", Age: 30}7 err := validate.Struct(person)8 if err != nil {9 fmt.Println(err)10 for _, err := range err.(validator.ValidationErrors) {11 fmt.Println(err.Namespace())12 fmt.Println(err.Field())13 fmt.Println(err.Tag())14 fmt.Println(err.ActualTag())15 fmt.Println(err.Kind())16 fmt.Println(err.Type())17 fmt.Println(err.Value())18 fmt.Println(err.Param())19 fmt.Println()20 }21 }22}

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 p := Person{Name: "Naveen", Age: 50}6 t := reflect.TypeOf(p)7 for i := 0; i < t.NumField(); i++ {8 field := t.Field(i)9 fmt.Printf("%v10 }11}12import (13type Person struct {14}15func (p Person) validate() bool {16 t := reflect.TypeOf(p)17 v := reflect.ValueOf(p)18 for i := 0; i < t.NumField(); i++ {19 field := t.Field(i)20 value := v.Field(i).Interface()21 if field.Tag.Get("required") == "true" {22 switch value.(type) {23 if value == "" {24 }25 if value == 0 {26 }27 }28 }29 if field.Tag.Get("max") != "" {30 max, _ := strconv.Atoi(field.Tag.Get("max"))31 switch value.(type) {32 if len(value.(string)) > max {33 }34 if value.(int) > max {35 }36 }37 }38 }39}40func main() {41 p := Person{Name: "Naveen", Age: 50}42 fmt.Println(p.validate())43 p1 := Person{Name: "Naveen", Age: 500}44 fmt.Println(p1.validate())45}

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type Student struct {3}4func main() {5 s := Student{Name: "Raj", Age: 20}6 fmt.Println(Validate(s))7}8func Validate(s interface{}) bool {9 v := reflect.ValueOf(s)10 for i := 0; i < v.NumField(); i++ {11 field := v.Field(i)12 validation := v.Type().Field(i).Tag.Get("required")13 if validation == "true" && field.String() == "" {14 }15 }16}17Related posts: How to use struct tags in Go? How to get the type of a variable in Golang? How to check if a variable is a function in Golang? How to convert a string to a number in Golang? How to get the size of a variable in Golang? How to use the defer keyword in Golang? How to use the interface{} type in Golang? How to use the range keyword in Golang? How to use the select keyword in Golang? How to use the switch keyword in Golang? How to use the for

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func main() {5 u := User{}6 t := reflect.TypeOf(u)7 for i:=0; i<t.NumField(); i++ {8 field := t.Field(i)9 fmt.Println("Name:", field.Name)10 fmt.Println("Type:", field.Type)11 fmt.Println("Tag: `required`:", field.Tag.Get("required"))12 fmt.Println("Tag: `min`:", field.Tag.Get("min"))13 fmt.Println("Tag: `max`:", field.Tag.Get("max"))14 fmt.Println("")15 }16}

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func main() {5 user := User{}6 t := reflect.TypeOf(user)7 for i := 0; i < t.NumField(); i++ {8 field := t.Field(i)9 fmt.Println("Name:", field.Name)10 fmt.Println("Type:", field.Type)11 fmt.Println("Tag: `required:", field.Tag.Get("required"), "`")12 fmt.Println("Tag: `max:", field.Tag.Get("max"), "`")13 fmt.Println("Tag: `min:", field.Tag.Get("min"), "`")14 }15}16import (17type User struct {18}19func main() {20 user := User{Name: "John", Age: 16}21 t := reflect.TypeOf(user)22 v := reflect.ValueOf(user)23 for i := 0; i < t.NumField(); i++ {24 field := t.Field(i)25 value := v.Field(i).Interface()26 if field.Tag.Get("required") == "true" {27 if value == "" {28 fmt.Println(field.Name, "is required")29 }30 }31 if field.Tag.Get("min") != "" {32 if value.(int) < 18 {33 fmt.Println(field.Name, "should be greater than 18")34 }35 }36 }37}38import (39type User struct {

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func (p Person) Tags() map[string]string {5 tags := make(map[string]string)6 v := reflect.ValueOf(p)7 t := v.Type()8 for i := 0; i < t.NumField(); i++ {9 tags[t.Field(i).Name] = t.Field(i).Tag.Get("valid")10 }11}12func main() {13 p := Person{14 }15 fmt.Println(p.Tags())16}17import (18type Person struct {19}20func (p Person) Tags() map[string]string {21 tags := make(map[string]string)22 v := reflect.ValueOf(p)23 t := v.Type()24 for i := 0; i < t.NumField(); i++ {25 tags[t.Field(i).Name] = t.Field(i).Tag.Get("valid")26 }27}28func main() {29 p := Person{30 }31 fmt.Println(p.Tags())32}33import (34type Person struct {35}36func (p Person) Tags() map[string]string {37 tags := make(map[string]string)38 v := reflect.ValueOf(p)39 t := v.Type()40 for i := 0; i < t.NumField(); i++ {41 tags[t.Field(i).Name] = t.Field(i).Tag.Get("valid")42 }43}44func main() {45 p := Person{46 }47 fmt.Println(p.Tags())48}

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1var validation = new Validation();2validation.Tags = new List<string>() { "tag1", "tag2" };3var result = validation.Validate();4var validation = new Validation();5validation.Tags = new List<string>() { "tag1", "tag2" };6var result = validation.Validate();7var validation = new Validation();8validation.Tags = new List<string>() { "tag1", "tag2" };9var result = validation.Validate();10var validation = new Validation();11validation.Tags = new List<string>() { "tag1", "tag2" };12var result = validation.Validate();13var validation = new Validation();14validation.Tags = new List<string>() { "tag1", "tag2" };15var result = validation.Validate();16var validation = new Validation();17validation.Tags = new List<string>() { "tag1", "tag2" };18var result = validation.Validate();19var validation = new Validation();20validation.Tags = new List<string>() { "tag1", "tag2" };21var result = validation.Validate();22var validation = new Validation();23validation.Tags = new List<string>() { "tag1", "tag2" };24var result = validation.Validate();25var validation = new Validation();26validation.Tags = new List<string>() { "tag1", "tag2" };27var result = validation.Validate();28var validation = new Validation();29validation.Tags = new List<string>() { "tag1", "tag2" };30var result = validation.Validate();31var validation = new Validation();32validation.Tags = new List<string>() { "tag1", "tag2" };33var result = validation.Validate();

Full Screen

Full Screen

Tags

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func validateStruct(s interface{}) (bool, error) {5 v := reflect.ValueOf(s)6 if v.Kind() == reflect.Ptr {7 v = v.Elem()8 }9 if v.Kind() != reflect.Struct {10 return false, errors.New("not a struct")11 }12 for i := 0; i < v.NumField(); i++ {13 field := v.Type().Field(i)14 tag := field.Tag.Get("validate")15 if tag == "required" {16 value := v.Field(i)17 if value.Kind() == reflect.String {18 if value.String() == "" {19 }20 } else if value.Kind() == reflect.Int {21 if value.Int() == 0 {22 }23 }24 }25 }26 if errMsg != "" {27 err = errors.New(strings.TrimSuffix(errMsg, ", "))28 }29}30func main() {31 user := User{

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful