...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/apivalidator/base_validator.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/apivalidator

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package apivalidator
    15  
    16  import (
    17  	"regexp"
    18  	"time"
    19  
    20  	"github.com/go-playground/validator/v10"
    21  	"github.com/robfig/cron/v3"
    22  )
    23  
    24  // NameValid can be used to check whether the given name is valid.
    25  func NameValid(fl validator.FieldLevel) bool {
    26  	name := fl.Field().String()
    27  	if name == "" {
    28  		return false
    29  	}
    30  
    31  	if len(name) > 63 {
    32  		return false
    33  	}
    34  
    35  	if !checkName(name) {
    36  		return false
    37  	}
    38  
    39  	return true
    40  }
    41  
    42  var namePattern = regexp.MustCompile(`^[-.\w]*$`)
    43  
    44  // checkName can be used to check resource names.
    45  func checkName(name string) bool {
    46  	return namePattern.MatchString(name)
    47  }
    48  
    49  // CronValid can be used to check whether the given cron valid.
    50  func CronValid(fl validator.FieldLevel) bool {
    51  	cr := fl.Field().String()
    52  	if cr == "" {
    53  		return true
    54  	}
    55  
    56  	if _, err := cron.ParseStandard(cr); err != nil {
    57  		return false
    58  	}
    59  
    60  	return true
    61  }
    62  
    63  // DurationValid can be used to check whether the given duration valid.
    64  func DurationValid(fl validator.FieldLevel) bool {
    65  	dur := fl.Field().String()
    66  	if dur == "" {
    67  		return true
    68  	}
    69  
    70  	_, err := time.ParseDuration(dur)
    71  	return err == nil
    72  }
    73