...

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

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

     1  // Copyright 2021 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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package apivalidator
    17  
    18  import (
    19  	"regexp"
    20  	"time"
    21  
    22  	"github.com/go-playground/validator/v10"
    23  	"github.com/robfig/cron/v3"
    24  )
    25  
    26  // NameValid can be used to check whether the given name is valid.
    27  func NameValid(fl validator.FieldLevel) bool {
    28  	name := fl.Field().String()
    29  	if name == "" {
    30  		return false
    31  	}
    32  
    33  	if len(name) > 63 {
    34  		return false
    35  	}
    36  
    37  	if !checkName(name) {
    38  		return false
    39  	}
    40  
    41  	return true
    42  }
    43  
    44  var namePattern = regexp.MustCompile(`^[-.\w]*$`)
    45  
    46  // checkName can be used to check resource names.
    47  func checkName(name string) bool {
    48  	return namePattern.MatchString(name)
    49  }
    50  
    51  // CronValid can be used to check whether the given cron valid.
    52  func CronValid(fl validator.FieldLevel) bool {
    53  	cr := fl.Field().String()
    54  	if cr == "" {
    55  		return true
    56  	}
    57  
    58  	if _, err := cron.ParseStandard(cr); err != nil {
    59  		return false
    60  	}
    61  
    62  	return true
    63  }
    64  
    65  // DurationValid can be used to check whether the given duration valid.
    66  func DurationValid(fl validator.FieldLevel) bool {
    67  	dur := fl.Field().String()
    68  	if dur == "" {
    69  		return true
    70  	}
    71  
    72  	_, err := time.ParseDuration(dur)
    73  	return err == nil
    74  }
    75