package validate import ( "base-go-v2/internal/errs" "errors" "reflect" "strings" ) // ValidateNotEmpty 校验结构体中指定字段不能为空 func ValidateNotEmpty(s interface{}, fields ...string) error { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = v.Elem() } for _, field := range fields { f := v.FieldByName(field) if !f.IsValid() { return errors.New("field " + field + " does not exist") } switch f.Kind() { case reflect.String: if strings.TrimSpace(f.String()) == "" { return errs.NewValidationError(field, "不能为空") } case reflect.Slice, reflect.Array, reflect.Map: if f.Len() == 0 { return errs.NewValidationError(field, "不能为空") } case reflect.Ptr, reflect.Interface: if f.IsNil() { return errs.NewValidationError(field, "不能为空") } default: continue } } return nil }