or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/go-protoc-gen-validate

Protoc plugin to generate polyglot message validators for protocol buffers

Workspace
tessl
Visibility
Public
Created
Last updated
Describes

pkg:github/bufbuild/protoc-gen-validate@1.2.x

To install, run

npx @tessl/cli install tessl/go-protoc-gen-validate@1.2.0

0

# protoc-gen-validate

1

2

protoc-gen-validate (PGV) is a protoc plugin that generates polyglot message validators for protocol buffer messages. It enables semantic validation rules for protocol buffer fields that cannot be expressed through basic type constraints alone, supporting Go, Java, C++, and Python with generated validation methods.

3

4

## Package Information

5

6

- **Package Name**: protoc-gen-validate

7

- **Package Type**: Go tool/protoc plugin

8

- **Language**: Go

9

- **Installation**: Download from [GitHub Releases](https://github.com/bufbuild/protoc-gen-validate/releases) or build from source

10

11

## Core Imports

12

13

For validation rules in proto files:

14

15

```protobuf

16

import "validate/validate.proto";

17

```

18

19

For Python runtime validation:

20

21

```python

22

from protoc_gen_validate.validator import validate, ValidationFailed

23

```

24

25

## Basic Usage

26

27

### Define validation rules in proto files:

28

29

```protobuf

30

syntax = "proto3";

31

package example;

32

import "validate/validate.proto";

33

34

message User {

35

uint64 id = 1 [(validate.rules).uint64.gt = 999];

36

string email = 2 [(validate.rules).string.email = true];

37

string name = 3 [(validate.rules).string = {

38

pattern: "^[A-Za-z]+( [A-Za-z]+)*$",

39

max_bytes: 256,

40

}];

41

}

42

```

43

44

### Generate validation code:

45

46

```bash

47

protoc \

48

-I . \

49

-I path/to/validate/ \

50

--go_out="./generated" \

51

--validate_out="lang=go:./generated" \

52

user.proto

53

```

54

55

### Use generated validators:

56

57

```go

58

user := &User{

59

Id: 1000,

60

Email: "user@example.com",

61

Name: "John Doe",

62

}

63

64

if err := user.Validate(); err != nil {

65

// Handle validation error

66

}

67

```

68

69

## Architecture

70

71

PGV uses a plugin architecture built on the protoc-gen-star framework:

72

73

- **Core Plugin**: Main protoc plugin entry point that processes proto files

74

- **Module System**: Extensible module for different target languages

75

- **Template Engine**: Language-specific code generation templates

76

- **Validation Schema**: Comprehensive protocol buffer extension definitions

77

- **Runtime Libraries**: Language-specific validation utilities

78

79

## Capabilities

80

81

### Core Plugin System

82

83

Provides the main protoc plugin functionality for code generation.

84

85

```go { .api }

86

// Main entry point for protoc plugin

87

func main()

88

89

// Core module interface

90

type Module struct {

91

*pgs.ModuleBase

92

ctx pgsgo.Context

93

lang string

94

}

95

96

func Validator() pgs.Module

97

func ValidatorForLanguage(lang string) pgs.Module

98

```

99

100

[Core Plugin System](./core-plugin.md)

101

102

### Validation Rules Schema

103

104

Defines comprehensive validation rules for all protocol buffer field types.

105

106

```protobuf { .api }

107

// Main field rules container

108

message FieldRules {

109

optional MessageRules message = 17;

110

oneof type {

111

FloatRules float = 1;

112

DoubleRules double = 2;

113

Int32Rules int32 = 3;

114

// ... all numeric types

115

StringRules string = 14;

116

BytesRules bytes = 15;

117

EnumRules enum = 16;

118

RepeatedRules repeated = 18;

119

MapRules map = 19;

120

AnyRules any = 20;

121

DurationRules duration = 21;

122

TimestampRules timestamp = 22;

123

}

124

}

125

126

// Protocol buffer extensions

127

extend google.protobuf.FieldOptions {

128

optional FieldRules rules = 1071;

129

}

130

```

131

132

[Validation Rules Schema](./validation-rules.md)

133

134

### Code Generation Templates

135

136

Template system for generating validation code in multiple languages.

137

138

```go { .api }

139

type RegisterFn func(tpl *template.Template, params pgs.Parameters)

140

type FilePathFn func(f pgs.File, ctx pgsgo.Context, tpl *template.Template) *pgs.FilePath

141

142

func Template(params pgs.Parameters) map[string][]*template.Template

143

func FilePathFor(tpl *template.Template) FilePathFn

144

```

145

146

[Code Generation Templates](./code-generation.md)

147

148

### Generated Code API

149

150

APIs provided by generated validation code in each target language.

151

152

```go { .api }

153

// Go generated methods

154

func (m *Message) Validate() error

155

func (m *Message) ValidateAll() error

156

```

157

158

```java { .api }

159

// Java validation interface

160

class ReflectiveValidatorIndex {

161

Validator validatorFor(Class<?> clazz)

162

}

163

```

164

165

```python { .api }

166

# Python runtime validation

167

def validate(msg) -> None # raises ValidationFailed

168

def print_validate(msg) -> None

169

```

170

171

[Generated Code API](./generated-code.md)

172

173

### Runtime Libraries

174

175

Language-specific runtime libraries and utilities for validation.

176

177

```python { .api }

178

class ValidationFailed(Exception):

179

"""Raised when message validation fails"""

180

pass

181

```

182

183

[Runtime Libraries](./runtime-libraries.md)

184

185

## Supported Languages

186

187

- **Go**: Full support with `Validate()` and `ValidateAll()` methods

188

- **Java**: Full support with ReflectiveValidatorIndex and gRPC interceptors

189

- **C++**: Header and implementation file generation

190

- **Python**: JIT runtime validation with caching

191

192

## Types

193

194

```go { .api }

195

// Module represents the core PGV module

196

type Module struct {

197

*pgs.ModuleBase

198

ctx pgsgo.Context

199

lang string

200

}

201

202

// Template registration function

203

type RegisterFn func(tpl *template.Template, params pgs.Parameters)

204

205

// File path generation function

206

type FilePathFn func(f pgs.File, ctx pgsgo.Context, tpl *template.Template) *pgs.FilePath

207

```

208

209

```protobuf { .api }

210

// Core validation rule types

211

message FieldRules { /* see validation rules schema */ }

212

message StringRules { /* string validation rules */ }

213

message MessageRules { /* message validation rules */ }

214

message RepeatedRules { /* repeated field validation rules */ }

215

message MapRules { /* map field validation rules */ }

216

```

217

218

```python { .api }

219

class ValidationFailed(Exception):

220

"""Exception raised when validation fails"""

221

pass

222

```