assignValidationMapping verifies that validation has been set once either in comp or in cfg. If validation has not been set assignValidationMapping generates a dummy function. Finally, assignValidationMapping sets validate in cfg. assignValidationMapping requires that the fieldByName function in cfg
(cfg *Config, comp Components)
| 472 | // Finally, assignValidationMapping sets validate in cfg. |
| 473 | // assignValidationMapping requires that the fieldByName function in cfg has been set. |
| 474 | func assignValidationMapping(cfg *Config, comp Components) error { |
| 475 | cfgOk := len(cfg.Validation) != 0 |
| 476 | compOk := comp.Validate != nil |
| 477 | |
| 478 | if cfgOk && compOk { |
| 479 | return fmt.Errorf("validation can't both be set in TOML and in Components") |
| 480 | } |
| 481 | |
| 482 | if !cfgOk && !compOk { |
| 483 | // Ok, validation not present, set a dummy funcition. |
| 484 | cfg.validate = func(r Record) (bool, FieldIndex) { |
| 485 | return true, 0 |
| 486 | } |
| 487 | return nil |
| 488 | } |
| 489 | |
| 490 | if compOk { |
| 491 | // Ok, validation has been set from Components. |
| 492 | cfg.validate = comp.Validate |
| 493 | return nil |
| 494 | } |
| 495 | |
| 496 | // Field validation has been set from Config, check errors and create the closures. |
| 497 | idxs := make([]FieldIndex, 0, len(cfg.Validation)) |
| 498 | regs := make([]*regexp.Regexp, 0, len(cfg.Validation)) |
| 499 | for k, v := range cfg.Validation { |
| 500 | i, ok := cfg.fieldByName(k) |
| 501 | if !ok { |
| 502 | return fmt.Errorf("validation field %q not exists", k) |
| 503 | } |
| 504 | reg, err := regexp.Compile(v) |
| 505 | if err != nil { |
| 506 | return fmt.Errorf("validation regex %q of field %q: %v", v, k, err) |
| 507 | } |
| 508 | idxs = append(idxs, i) |
| 509 | regs = append(regs, reg) |
| 510 | } |
| 511 | |
| 512 | cfg.validate = func(r Record) (bool, FieldIndex) { |
| 513 | for i, idx := range idxs { |
| 514 | reg := regs[i] |
| 515 | if !reg.Match(r.Get(idx)) { |
| 516 | return false, idx |
| 517 | } |
| 518 | } |
| 519 | return true, 0 |
| 520 | } |
| 521 | |
| 522 | return nil |
| 523 | } |
| 524 | |
| 525 | // RequiredFields returns the names of the underlying configuration structure |
| 526 | // fields which are tagged as required. To tag a field as being required, a |