Repository: ogen-go/ogen
Pull request #728 (2022-12-19 15:07:32)

feat(gen): support user-defined JSON Schema formats

codecov[bot]: # [Codecov](https://codecov.io/gh/ogen-go/ogen/pull/728?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go) Report
Base: **74.38**% // Head: **73.80**% // Decreases project coverage by **`-0.58%`** :warning:
> Coverage data is based on head [(`7abfdd8`)](https://codecov.io/gh/ogen-go/ogen/pull/728?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go) compared to base [(`c4da0eb`)](https://codecov.io/gh/ogen-go/ogen/commit/c4da0eb9c4d343ca9b8df84fc060f842f4bc043e?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go).
> Patch coverage: 9.48% of modified lines in pull request are covered.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main     #728      +/-   ##
==========================================
- Coverage   74.38%   73.80%   -0.59%     
==========================================
  Files         176      178       +2     
  Lines       12734    12845     +111     
==========================================
+ Hits         9472     9480       +8     
- Misses       2781     2877      +96     
- Partials      481      488       +7     
```


| [Impacted Files](https://codecov.io/gh/ogen-go/ogen/pull/728?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go) | Coverage Δ | |
|---|---|---|
| [gen/ir/custom\_format.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL2lyL2N1c3RvbV9mb3JtYXQuZ28=) | `0.00% <0.00%> (ø)` | |
| [gen/ir/primitive.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL2lyL3ByaW1pdGl2ZS5nbw==) | `76.92% <0.00%> (-3.08%)` | :arrow_down: |
| [gen/ir/type.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL2lyL3R5cGUuZ28=) | `75.39% <0.00%> (-3.77%)` | :arrow_down: |
| [gen/options.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL29wdGlvbnMuZ28=) | `14.28% <0.00%> (-2.39%)` | :arrow_down: |
| [gen/schema\_gen.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL3NjaGVtYV9nZW4uZ28=) | `82.23% <ø> (-0.08%)` | :arrow_down: |
| [internal/integration/phonetype/phone.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-aW50ZXJuYWwvaW50ZWdyYXRpb24vcGhvbmV0eXBlL3Bob25lLmdv) | `0.00% <0.00%> (ø)` | |
| [gen/generator.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL2dlbmVyYXRvci5nbw==) | `44.64% <8.06%> (-14.00%)` | :arrow_down: |
| [gen/schema\_gen\_primitive.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL3NjaGVtYV9nZW5fcHJpbWl0aXZlLmdv) | `86.70% <28.57%> (-2.71%)` | :arrow_down: |
| [gen/write.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL3dyaXRlLmdv) | `86.26% <30.00%> (-2.53%)` | :arrow_down: |
| [gen/gen\_schema.go](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go#diff-Z2VuL2dlbl9zY2hlbWEuZ28=) | `69.69% <100.00%> (+0.30%)` | :arrow_up: |
| ... and [2 more](https://codecov.io/gh/ogen-go/ogen/pull/728/diff?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go) | |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go)

</details>

[:umbrella: View full report at Codecov](https://codecov.io/gh/ogen-go/ogen/pull/728?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go).   
:loudspeaker: Do you have feedback about the report comment? [Let us know in this issue](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ogen-go).


Patch:
diff --git a/gen/_template/globals.tmpl b/gen/_template/globals.tmpl
index c1e163a8..1ec7eb8b 100644
--- a/gen/_template/globals.tmpl
+++ b/gen/_template/globals.tmpl
@@ -24,6 +24,19 @@ var ratMap = map[string]*big.Rat{
 }
 {{- end }}
 
+{{- with $cfs := $.CustomFormats }}
+var (
+	{{- range $cf := $cfs }}
+	format{{ $cf }} = func() (r struct{
+    	{{ $cf.JSON.Go }}
+    	{{ $cf.Text.Go }}
+	}) {
+		return r
+	}
+	{{- end }}
+)
+{{- end }}
+
 {{- if or $.ServerEnabled $.ClientEnabled }}
 var (
 	{{- if $.ClientEnabled }}
diff --git a/gen/_template/header.tmpl b/gen/_template/header.tmpl
index 30d3c43a..be045efa 100644
--- a/gen/_template/header.tmpl
+++ b/gen/_template/header.tmpl
@@ -68,5 +68,9 @@ import (
 	"github.com/ogen-go/ogen/otelogen"
 	"github.com/ogen-go/ogen/uri"
 	"github.com/ogen-go/ogen/validate"
+
+	{{- range $import := $.CustomImports }}
+	{{ $import }}
+	{{- end }}
 )
 {{ end }}
diff --git a/gen/_template/json/decode.tmpl b/gen/_template/json/decode.tmpl
index c07ccfb8..5531ec2f 100644
--- a/gen/_template/json/decode.tmpl
+++ b/gen/_template/json/decode.tmpl
@@ -47,6 +47,10 @@ if err := d.Arr(func(d *jx.Decoder) error {
 	if err := {{ $.Var }}.Decode(d, json.Decode{{ $g.JSON.Format }}); err != nil {
 		return err
 	}
+{{- else if $g.CustomFormat }}
+	if err := {{ $.Var }}.Decode(d, format{{ $g.CustomFormat }}().DecodeJSON); err != nil {
+		return err
+	}
 {{- else }}
 	if err := {{ $.Var }}.Decode(d); err != nil {
 		return err
@@ -88,6 +92,12 @@ if err := d.Arr(func(d *jx.Decoder) error {
 		if err != nil {
 			return err
 		}
+    {{- else if $t.CustomFormat }}
+		v, err := format{{ $t.CustomFormat }}().DecodeJSON(d)
+        {{ $.Var }} = v
+		if err != nil {
+			return err
+		}
 	{{- else }}
         {{ errorf "unsupported kind: %s" $t.Kind }}
 	{{- end }}
diff --git a/gen/_template/json/encode.tmpl b/gen/_template/json/encode.tmpl
index 10f92cb6..1f0658a0 100644
--- a/gen/_template/json/encode.tmpl
+++ b/gen/_template/json/encode.tmpl
@@ -11,17 +11,31 @@ e.FieldStart({{ $.Tag.EscapedJSON }})
 {{- define "json/enc_generic" -}}
 {{- $g := $.Type.GenericOf -}}
 {{- $v := $.Type.GenericVariant -}}
+
 {{- if $v.Optional -}}
-	if {{ $.Var }}.Set {
-		{{- template "json/enc_field" $ }}
-		{{ $.Var }}.Encode(e{{ if $g.Format }}, json.Encode{{ $g.JSON.Format }}{{ end }})
-	}
-{{- else -}}
-	{{- template "json/enc_field" $ }}
-	{{ $.Var }}.Encode(e{{ if $g.Format }}, json.Encode{{ $g.JSON.Format }}{{ end }})
+if {{ $.Var }}.Set {
+	{{- template "json/enc_generic_field" $ }}
+}
+{{- else }}
+    {{- template "json/enc_generic_field" $ }}
 {{- end -}}
+
 {{- end }}
 
+{{- define "json/enc_generic_field" -}}
+{{- $g := $.Type.GenericOf -}}
+{{- $v := $.Type.GenericVariant -}}
+
+{{- template "json/enc_field" $ }}
+{{- if $g.Format }}
+	{{ $.Var }}.Encode(e, json.Encode{{ $g.JSON.Format }})
+{{- else if $g.CustomFormat }}
+    {{ $.Var }}.Encode(e, format{{ $g.CustomFormat }}().EncodeJSON)
+{{- else }}
+    {{ $.Var }}.Encode(e)
+{{- end }}
+
+{{- end }}
 
 {{/* Encode array with all elements */}}
 {{- define "json/enc_array_elems" }}
@@ -101,6 +115,9 @@ e.FieldStart({{ $.Tag.EscapedJSON }})
 	{{- else if $j.Fn -}}
 		{{- template "json/enc_field" $ }}
 		e.{{ $j.Fn }}({{ $.Var }})
+    {{- else if $t.CustomFormat }}
+        {{- template "json/enc_field" $ }}
+		format{{ $t.CustomFormat }}().EncodeJSON(e, {{ $.Var }})
 	{{- else -}}
 		{{ errorf "unsupported: %s" $t }}
 	{{- end }}
diff --git a/gen/_template/json/encoders_generic.tmpl b/gen/_template/json/encoders_generic.tmpl
index 40545fb2..344a27c6 100644
--- a/gen/_template/json/encoders_generic.tmpl
+++ b/gen/_template/json/encoders_generic.tmpl
@@ -3,7 +3,7 @@
 {{ $g := $.GenericOf }}
 {{ $v := $.GenericVariant }}
 // Encode encodes {{ $g.Go }} as json.
-func (o {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder{{ if $g.Format }}, format func(*jx.Encoder, {{ $g.Go }}){{ end }}) {
+func (o {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder{{ if or $g.Format $g.CustomFormat }}, format func(*jx.Encoder, {{ $g.Go }}){{ end }}) {
 {{- if $v.Optional }}
 	if !o.Set {
 		return
@@ -19,6 +19,8 @@ func (o {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder{{ if $g.Format }}, format
 	format(e, o.Value)
 {{- else if $g.JSON.Format }}
 	json.Encode{{ $g.JSON.Format }}(e, o.Value)
+{{- else if $g.CustomFormat }}
+	format{{ $g.CustomFormat }}().EncodeJSON(e, o.Value)
 {{- else if $g.JSON.Fn }}
 	{{- if $g.IsAny }}
 		{{ errorf "unexpected optional any" }}
@@ -36,7 +38,7 @@ func (o {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder{{ if $g.Format }}, format
 }
 
 // Decode decodes {{ $g.Go }} from json.
-func (o *{{ $.Name }}) Decode(d *jx.Decoder{{ if $g.Format }}, format func(*jx.Decoder) ({{ $g.Go }}, error){{ end }}) error {
+func (o *{{ $.Name }}) Decode(d *jx.Decoder{{ if or $g.Format $g.CustomFormat }}, format func(*jx.Decoder) ({{ $g.Go }}, error){{ end }}) error {
 	if o == nil {
 		return errors.New({{ printf "invalid: unable to decode %s to nil" $.Name | quote }})
 	}
@@ -74,6 +76,12 @@ func (o *{{ $.Name }}) Decode(d *jx.Decoder{{ if $g.Format }}, format func(*jx.D
 			return err
 		}
 		o.Value = v
+	{{- else if $g.CustomFormat }}
+		v, err := format{{ $g.CustomFormat }}().DecodeJSON(d)
+		if err != nil {
+			return err
+		}
+		o.Value = v
 	{{- else if or ($g.IsStruct) ($g.IsEnum) ($g.IsPointer) ($g.IsSum) ($g.IsAlias)  }}
 		if err := o.Value.Decode(d); err != nil {
 			return err
diff --git a/gen/_template/json/stdmarshaler.tmpl b/gen/_template/json/stdmarshaler.tmpl
index 192b74b2..52019a89 100644
--- a/gen/_template/json/stdmarshaler.tmpl
+++ b/gen/_template/json/stdmarshaler.tmpl
@@ -4,22 +4,34 @@
 // MarshalJSON implements stdjson.Marshaler.
 func (s {{ $.ReadOnlyReceiver }}) MarshalJSON() ([]byte, error) {
 	e := jx.Encoder{}
-	{{- if $.IsGeneric }}
-	s.Encode(&e{{ if $g.Format }}, json.Encode{{ $g.JSON.Format }}{{ end }})
+{{- if $.IsGeneric }}
+	{{- if $g.Format }}
+	s.Encode(&e, json.Encode{{ $g.JSON.Format }})
+	{{- else if $g.CustomFormat }}
+	s.Encode(&e, format{{ $g.CustomFormat }}().EncodeJSON)
 	{{- else }}
 	s.Encode(&e)
 	{{- end }}
+{{- else }}
+	s.Encode(&e)
+{{- end }}
 	return e.Bytes(), nil
 }
 
 // UnmarshalJSON implements stdjson.Unmarshaler.
 func (s *{{ $.Name }}) UnmarshalJSON(data []byte) error {
 	d := jx.DecodeBytes(data)
-	{{- if $.IsGeneric }}
-	return s.Decode(d{{ if $g.Format }}, json.Decode{{ $g.JSON.Format }}{{ end }})
+{{- if $.IsGeneric }}
+	{{- if $g.Format }}
+	return s.Decode(d, json.Decode{{ $g.JSON.Format }})
+	{{- else if $g.CustomFormat }}
+	return s.Decode(d, format{{ $g.CustomFormat }}().DecodeJSON)
 	{{- else }}
 	return s.Decode(d)
 	{{- end }}
+{{- else }}
+	return s.Decode(d)
+{{- end }}
 }
 
 {{ end }}
diff --git a/gen/_template/uri/decode.tmpl b/gen/_template/uri/decode.tmpl
index 012aa9e8..c6cbf6d7 100644
--- a/gen/_template/uri/decode.tmpl
+++ b/gen/_template/uri/decode.tmpl
@@ -3,7 +3,20 @@
 {{- $t := $.Type }}
 {{- $var := $.Var }}
 {{- $tmpVar := camelSpecial (printf "%sVal" $var) }}
-{{- if $t.IsPrimitive }}
+{{- if $t.CustomFormat }}
+	val, err := d.DecodeValue()
+	if err != nil {
+		return err
+	}
+
+	c, err := format{{ $t.CustomFormat }}().DecodeText(val)
+	if err != nil {
+		return err
+	}
+
+	{{ $var }} = c
+	return nil
+{{- else if $t.IsPrimitive }}
 	val, err := d.DecodeValue()
 	if err != nil {
 		return err
diff --git a/gen/_template/uri/encode.tmpl b/gen/_template/uri/encode.tmpl
index 42e862da..54f952ea 100644
--- a/gen/_template/uri/encode.tmpl
+++ b/gen/_template/uri/encode.tmpl
@@ -2,7 +2,9 @@
 {{- define "uri/encode" }}
 {{- $t := $.Type }}
 {{- $var := $.Var }}
-{{- if $t.IsPrimitive }}
+{{- if $t.CustomFormat }}
+	return e.EncodeValue(format{{ $t.CustomFormat }}().EncodeText({{ $var }}))
+{{- else if $t.IsPrimitive }}
 	return e.EncodeValue(conv.{{ $t.ToString }}({{ $var }}))
 {{- else if $t.IsEnum }}
 	return e.EncodeValue(conv.{{ $t.ToString }}({{ $t.Primitive.String }}({{ $var }})))
diff --git a/gen/gen_schema.go b/gen/gen_schema.go
index de491ae4..f3c84ecc 100644
--- a/gen/gen_schema.go
+++ b/gen/gen_schema.go
@@ -41,6 +41,7 @@ func (g *Generator) generateSchema(ctx *genctx, name string, schema *jsonschema.
 	gen := newSchemaGen(ctx.lookupRef)
 	gen.log = g.log.Named("schemagen")
 	gen.fail = g.fail
+	gen.customFormats = g.customFormats
 
 	t, err := gen.generate(name, schema, optional)
 	if err != nil {
diff --git a/gen/generator.go b/gen/generator.go
index 09607fa3..faab9dbb 100644
--- a/gen/generator.go
+++ b/gen/generator.go
@@ -1,6 +1,9 @@
 package gen
 
 import (
+	"fmt"
+	"go/token"
+	"reflect"
 	"strings"
 
 	"github.com/go-faster/errors"
@@ -9,6 +12,7 @@ import (
 
 	"github.com/ogen-go/ogen"
 	"github.com/ogen-go/ogen/gen/ir"
+	"github.com/ogen-go/ogen/internal/xmaps"
 	"github.com/ogen-go/ogen/internal/xslices"
 	"github.com/ogen-go/ogen/jsonschema"
 	"github.com/ogen-go/ogen/openapi"
@@ -28,6 +32,9 @@ type Generator struct {
 	webhookRouter WebhookRouter
 	router        Router
 
+	customFormats map[jsonschema.SchemaType]map[string]ir.CustomFormat
+	imports       []string
+
 	log *zap.Logger
 }
 
@@ -60,9 +67,14 @@ func NewGenerator(spec *ogen.Spec, opts Options) (*Generator, error) {
 		errType:       nil,
 		webhookRouter: WebhookRouter{},
 		router:        Router{},
+		customFormats: map[jsonschema.SchemaType]map[string]ir.CustomFormat{},
 		log:           opts.Logger,
 	}
 
+	if err := g.makeCustomFormats(); err != nil {
+		return nil, errors.Wrap(err, "make custom formats")
+	}
+
 	if err := g.makeIR(api); err != nil {
 		return nil, errors.Wrap(err, "make ir")
 	}
@@ -74,6 +86,80 @@ func NewGenerator(spec *ogen.Spec, opts Options) (*Generator, error) {
 	return g, nil
 }
 
+func (g *Generator) makeCustomFormats() error {
+	importPaths := map[string]string{}
+
+	makeExternal := func(typ reflect.Type) (ir.ExternalType, error) {
+		path := typ.PkgPath()
+		if path == "main" {
+			return ir.ExternalType{}, errors.New("type must be in importable package")
+		}
+		if n := typ.Name(); n == "" || !token.IsExported(n) {
+			return ir.ExternalType{}, errors.New("type must be named and exported")
+		}
+
+		importName, ok := importPaths[path]
+		if !ok {
+			importName = fmt.Sprintf("custom%d", len(importPaths))
+			importPaths[path] = importName
+			g.imports = append(g.imports, fmt.Sprintf("%s %q", importName, path))
+		}
+
+		return ir.ExternalType{
+			Pkg:  importName,
+			Type: typ,
+		}, nil
+	}
+
+	for _, jsonTyp := range xmaps.SortedKeys(g.opt.CustomFormats) {
+		formats := g.opt.CustomFormats[jsonTyp]
+		for _, format := range xmaps.SortedKeys(formats) {
+			def := formats[format]
+
+			if _, ok := g.customFormats[jsonTyp]; !ok {
+				g.customFormats[jsonTyp] = map[string]ir.CustomFormat{}
+			}
+
+			f, err := func() (f ir.CustomFormat, _ error) {
+				goName, err := pascalNonEmpty(format)
+				if err != nil {
+					return f, errors.Wrap(err, "generate go name")
+				}
+
+				typ, err := makeExternal(def.typ)
+				if err != nil {
+					return f, errors.Wrap(err, "format type")
+				}
+
+				json, err := makeExternal(def.json)
+				if err != nil {
+					return f, errors.Wrap(err, "json encoding")
+				}
+
+				text, err := makeExternal(def.text)
+				if err != nil {
+					return f, errors.Wrap(err, "text encoding")
+				}
+
+				return ir.CustomFormat{
+					Name:   format,
+					GoName: goName,
+					Type:   typ,
+					JSON:   json,
+					Text:   text,
+				}, nil
+			}()
+			if err != nil {
+				return errors.Wrapf(err, "custom format %q:%q", jsonTyp, format)
+			}
+
+			g.customFormats[jsonTyp][format] = f
+		}
+	}
+
+	return nil
+}
+
 func (g *Generator) makeIR(api *openapi.API) error {
 	if err := g.makeServers(api.Servers); err != nil {
 		return errors.Wrap(err, "servers")
diff --git a/gen/ir/custom_format.go b/gen/ir/custom_format.go
new file mode 100644
index 00000000..03ded62a
--- /dev/null
+++ b/gen/ir/custom_format.go
@@ -0,0 +1,37 @@
+package ir
+
+import (
+	"fmt"
+	"reflect"
+)
+
+// ExternalType defines external type.
+type ExternalType struct {
+	// Pkg is name of the imported package.
+	Pkg  string
+	Type reflect.Type
+}
+
+// Go returns valid Go type for this ExternalType.
+func (c ExternalType) Go() string {
+	return fmt.Sprintf("%s.%s", c.Pkg, c.Type.Name())
+}
+
+// CustomFormat defines custom format type.
+type CustomFormat struct {
+	// Name is name of custom format.
+	Name string
+	// GoName is valid Go name for this custom format.
+	GoName string
+	// Type is type of custom format.
+	Type ExternalType
+	// JSON is JSON encoder/decoder for custom format.
+	JSON ExternalType
+	// Text is text encoder/decoder for custom format.
+	Text ExternalType
+}
+
+// String returns string representation of CustomFormat.
+func (c *CustomFormat) String() string {
+	return c.GoName
+}
diff --git a/gen/ir/primitive.go b/gen/ir/primitive.go
index d31997b2..9fdd4e11 100644
--- a/gen/ir/primitive.go
+++ b/gen/ir/primitive.go
@@ -50,6 +50,8 @@ func (p PrimitiveType) String() string {
 		return "url.URL"
 	case File:
 		return "ht.MultipartFile"
+	case Custom:
+		return "<custom>"
 	default:
 		panic(fmt.Sprintf("unexpected PrimitiveType: %d", p))
 	}
@@ -84,4 +86,5 @@ const (
 	IP
 	URL
 	File
+	Custom
 )
diff --git a/gen/ir/type.go b/gen/ir/type.go
index 0b1debb9..d9465220 100644
--- a/gen/ir/type.go
+++ b/gen/ir/type.go
@@ -53,6 +53,7 @@ type Type struct {
 	Kind                Kind                // kind
 	Name                string              // only for struct, alias, interface, enum, stream, generic, map, sum
 	Primitive           PrimitiveType       // only for primitive, enum
+	CustomFormat        *CustomFormat       // only for primitive
 	AliasTo             *Type               // only for alias
 	PointerTo           *Type               // only for pointer
 	SumOf               []*Type             // only for sum
@@ -70,7 +71,6 @@ type Type struct {
 	MapPattern          ogenregex.Regexp    // only for map
 	DenyAdditionalProps bool                // only for map and struct
 	Validators          Validators
-
 	// Features contains a set of features the type must implement.
 	// Available features: 'json', 'uri'.
 	//
@@ -154,6 +154,9 @@ func (t *Type) Is(vs ...Kind) bool {
 func (t *Type) Go() string {
 	switch t.Kind {
 	case KindPrimitive:
+		if cf := t.CustomFormat; cf != nil {
+			return cf.Type.Go()
+		}
 		return t.Primitive.String()
 	case KindAny:
 		return "jx.Raw"
@@ -172,6 +175,9 @@ func (t *Type) Go() string {
 func (t *Type) NamePostfix() string {
 	switch t.Kind {
 	case KindPrimitive:
+		if cf := t.CustomFormat; cf != nil {
+			return cf.GoName
+		}
 		if t.Primitive == Null {
 			return "Null"
 		}
diff --git a/gen/ir/validation.go b/gen/ir/validation.go
index a8d44393..6a9e9fd2 100644
--- a/gen/ir/validation.go
+++ b/gen/ir/validation.go
@@ -146,7 +146,10 @@ func (t *Type) needValidation(path *walkpath) (result bool) {
 			return true
 		}
 		if t.Validators.String.Set() {
-			return true
+			switch t.Primitive {
+			case String, ByteSlice:
+				return true
+			}
 		}
 		return false
 	case KindEnum:
diff --git a/gen/options.go b/gen/options.go
index 8b2ef33d..d3e2b77f 100644
--- a/gen/options.go
+++ b/gen/options.go
@@ -2,10 +2,12 @@ package gen
 
 import (
 	"net/url"
+	"reflect"
 	"regexp"
 	"strings"
 
 	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
 	"go.uber.org/zap"
 	"golang.org/x/exp/slices"
 
@@ -33,6 +35,8 @@ type Options struct {
 	// InferSchemaType enables type inference for schemas. Schema parser will try to detect schema type
 	// by its properties.
 	InferSchemaType bool
+	// CustomFormats sets custom formats.
+	CustomFormats CustomFormatsMap
 
 	// AllowRemote enables remote references resolving.
 	//
@@ -119,3 +123,36 @@ func (f Filters) accept(op *openapi.Operation) bool {
 
 	return true
 }
+
+// CustomFormatsMap is map of custom formats.
+type CustomFormatsMap = map[jsonschema.SchemaType]map[string]CustomFormatDef
+
+// CustomFormatDef defines custom format type.
+type CustomFormatDef struct {
+	typ  reflect.Type
+	json reflect.Type
+	text reflect.Type
+}
+
+// CustomFormat returns custom format definition.
+func CustomFormat[
+	T any,
+	JSON interface {
+		~struct{} // Enforce implementation without state.
+
+		EncodeJSON(*jx.Encoder, T)
+		DecodeJSON(*jx.Decoder) (T, error)
+	},
+	Text interface {
+		~struct{} // Enforce implementation without state.
+
+		EncodeText(T) string
+		DecodeText(string) (T, error)
+	},
+]() CustomFormatDef {
+	return CustomFormatDef{
+		typ:  reflect.TypeOf(new(T)).Elem(),
+		json: reflect.TypeOf(new(JSON)).Elem(),
+		text: reflect.TypeOf(new(Text)).Elem(),
+	}
+}
diff --git a/gen/schema_gen.go b/gen/schema_gen.go
index b98a3928..cc7737fa 100644
--- a/gen/schema_gen.go
+++ b/gen/schema_gen.go
@@ -19,12 +19,12 @@ type schemaGen struct {
 	nameRef   func(ref jsonschema.Ref) (string, error)
 	fail      func(err error) error
 
-	log *zap.Logger
+	customFormats map[jsonschema.SchemaType]map[string]ir.CustomFormat
+	log           *zap.Logger
 }
 
 func newSchemaGen(lookupRef func(ref jsonschema.Ref) (*ir.Type, bool)) *schemaGen {
 	return &schemaGen{
-		side:      nil,
 		localRefs: map[jsonschema.Ref]*ir.Type{},
 		lookupRef: lookupRef,
 		nameRef: func(ref jsonschema.Ref) (string, error) {
@@ -37,7 +37,8 @@ func newSchemaGen(lookupRef func(ref jsonschema.Ref) (*ir.Type, bool)) *schemaGe
 		fail: func(err error) error {
 			return err
 		},
-		log: zap.NewNop(),
+		customFormats: map[jsonschema.SchemaType]map[string]ir.CustomFormat{},
+		log:           zap.NewNop(),
 	}
 }
 
@@ -280,6 +281,16 @@ func (g *schemaGen) generate2(name string, schema *jsonschema.Schema) (ret *ir.T
 			if err := t.Validators.SetString(schema); err != nil {
 				return nil, errors.Wrap(err, "string validator")
 			}
+			switch t.Primitive {
+			case ir.String, ir.ByteSlice:
+			default:
+				g.log.Warn("String validator cannot be applied to non-string type and will be ignored",
+					zapPosition(schema),
+					zap.String("type", string(schema.Type)),
+					zap.String("format", schema.Format),
+					zap.String("go_type", t.Go()),
+				)
+			}
 		case jsonschema.Integer:
 			if err := t.Validators.SetInt(schema); err != nil {
 				return nil, errors.Wrap(err, "int validator")
diff --git a/gen/schema_gen_primitive.go b/gen/schema_gen_primitive.go
index e5df7cd4..3c091bb1 100644
--- a/gen/schema_gen_primitive.go
+++ b/gen/schema_gen_primitive.go
@@ -12,7 +12,7 @@ import (
 )
 
 func (g *schemaGen) primitive(name string, schema *jsonschema.Schema) (*ir.Type, error) {
-	t := parseSimple(schema)
+	t := g.parseSimple(schema)
 
 	if len(schema.Enum) > 0 {
 		return g.enum(name, t, schema)
@@ -146,12 +146,17 @@ func (g *schemaGen) enum(name string, t *ir.Type, schema *jsonschema.Schema) (*i
 	}, nil
 }
 
-func parseSimple(schema *jsonschema.Schema) *ir.Type {
+func (g *schemaGen) parseSimple(schema *jsonschema.Schema) *ir.Type {
 	mapping := TypeFormatMapping()
 
 	// TODO(tdakkota): check ContentEncoding field
 	t, found := mapping[schema.Type][schema.Format]
 	if !found {
+		if custom, ok := g.customFormats[schema.Type][schema.Format]; ok {
+			typ := ir.Primitive(ir.Custom, schema)
+			typ.CustomFormat = &custom
+			return typ
+		}
 		// Fallback to default.
 		t = mapping[schema.Type][""]
 	}
diff --git a/gen/write.go b/gen/write.go
index b940e0c2..22c941ce 100644
--- a/gen/write.go
+++ b/gen/write.go
@@ -33,6 +33,8 @@ type TemplateConfig struct {
 	Securities    map[string]*ir.Security
 	Router        Router
 	WebhookRouter WebhookRouter
+	CustomImports []string
+	CustomFormats []ir.CustomFormat
 	ClientEnabled bool
 	ServerEnabled bool
 
@@ -222,6 +224,16 @@ func (g *Generator) WriteSource(fs FileSystem, pkgName string) error {
 		types[name] = t
 	}
 
+	var customFormats []ir.CustomFormat
+	for _, formats := range g.customFormats {
+		for _, format := range formats {
+			customFormats = append(customFormats, format)
+		}
+	}
+	slices.SortStableFunc(customFormats, func(i, j ir.CustomFormat) bool {
+		return i.Name < j.Name
+	})
+
 	cfg := TemplateConfig{
 		Package:       pkgName,
 		Operations:    g.operations,
@@ -234,6 +246,8 @@ func (g *Generator) WriteSource(fs FileSystem, pkgName string) error {
 		Securities:    g.securities,
 		Router:        g.router,
 		WebhookRouter: g.webhookRouter,
+		CustomImports: g.imports,
+		CustomFormats: customFormats,
 		ClientEnabled: !g.opt.NoClient,
 		ServerEnabled: !g.opt.NoServer,
 		skipTestRegex: g.opt.SkipTestRegex,
diff --git a/internal/integration/cmd/customformats/main.go b/internal/integration/cmd/customformats/main.go
new file mode 100644
index 00000000..dd6bc8fb
--- /dev/null
+++ b/internal/integration/cmd/customformats/main.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+	"flag"
+	"os"
+	"path/filepath"
+
+	"github.com/go-faster/errors"
+	"go.uber.org/zap"
+
+	"github.com/ogen-go/ogen"
+	"github.com/ogen-go/ogen/gen"
+	"github.com/ogen-go/ogen/gen/genfs"
+	"github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	"github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+	"github.com/ogen-go/ogen/internal/location"
+	"github.com/ogen-go/ogen/internal/ogenzap"
+	"github.com/ogen-go/ogen/internal/urlpath"
+	"github.com/ogen-go/ogen/jsonschema"
+)
+
+func run(specPath, targetDir string) error {
+	specPath, err := filepath.Abs(filepath.Clean(specPath))
+	if err != nil {
+		return err
+	}
+
+	data, err := os.ReadFile(specPath)
+	if err != nil {
+		return err
+	}
+
+	spec, err := ogen.Parse(data)
+	if err != nil {
+		return errors.Wrap(err, "parse spec")
+	}
+
+	u, err := urlpath.URLFromFilePath(specPath)
+	if err != nil {
+		return errors.Wrap(err, "convert file path to url")
+	}
+
+	l, err := ogenzap.Create(ogenzap.Options{Level: zap.DebugLevel})
+	if err != nil {
+		return errors.Wrap(err, "create logger")
+	}
+	defer func() {
+		_ = l.Sync()
+	}()
+
+	_, fileName := filepath.Split(specPath)
+	g, err := gen.NewGenerator(spec, gen.Options{
+		RootURL: u,
+		CustomFormats: gen.CustomFormatsMap{
+			jsonschema.String: {
+				"phone": gen.CustomFormat[
+					phonetype.Phone,
+					phonetype.JSONPhoneEncoding,
+					phonetype.TextPhoneEncoding,
+				](),
+				"rgba": gen.CustomFormat[
+					rgbatype.RGBA,
+					rgbatype.JSONRGBAEncoding,
+					rgbatype.TextRGBAEncoding,
+				](),
+			},
+		},
+		File:   location.NewFile(fileName, specPath, data),
+		Logger: l,
+	})
+	if err != nil {
+		return errors.Wrap(err, "generate")
+	}
+
+	if err := os.MkdirAll(targetDir, 0o750); err != nil {
+		return err
+	}
+	fs := genfs.FormattedSource{
+		// FIXME(tdakkota): write source uses imports.Process which also uses go/format.
+		// 	So, there is no reason to format source twice or provide a flag to disable formatting.
+		Format: false,
+		Root:   targetDir,
+	}
+	if err := g.WriteSource(fs, "api"); err != nil {
+		return errors.Wrap(err, "write")
+	}
+
+	return nil
+}
+
+func main() {
+	set := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
+	if err := set.Parse(os.Args[1:]); err != nil {
+		panic(err)
+	}
+
+	specPath := set.Arg(0)
+	if specPath == "" {
+		panic("spec path is required")
+	}
+
+	targetDir := set.Arg(1)
+	if targetDir == "" {
+		targetDir = "api"
+	}
+
+	if err := run(specPath, targetDir); err != nil {
+		panic(err)
+	}
+}
diff --git a/internal/integration/customformats/phonetype/phone.go b/internal/integration/customformats/phonetype/phone.go
new file mode 100644
index 00000000..3536cc32
--- /dev/null
+++ b/internal/integration/customformats/phonetype/phone.go
@@ -0,0 +1,42 @@
+// Package phonetype defines a custom format for phone numbers.
+package phonetype
+
+import (
+	"regexp"
+
+	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
+)
+
+type Phone string
+
+var phoneRegexp = regexp.MustCompile(`^\+\d+$`)
+
+type JSONPhoneEncoding struct{}
+
+func (JSONPhoneEncoding) EncodeJSON(e *jx.Encoder, v Phone) {
+	var t TextPhoneEncoding
+	e.Str(t.EncodeText(v))
+}
+
+func (JSONPhoneEncoding) DecodeJSON(d *jx.Decoder) (v Phone, _ error) {
+	s, err := d.Str()
+	if err != nil {
+		return v, err
+	}
+	var t TextPhoneEncoding
+	return t.DecodeText(s)
+}
+
+type TextPhoneEncoding struct{}
+
+func (TextPhoneEncoding) EncodeText(v Phone) string {
+	return string(v)
+}
+
+func (TextPhoneEncoding) DecodeText(s string) (v Phone, _ error) {
+	if !phoneRegexp.MatchString(s) {
+		return v, errors.Errorf("invalid phone %q", s)
+	}
+	return Phone(s), nil
+}
diff --git a/internal/integration/customformats/rgbatype/rgba.go b/internal/integration/customformats/rgbatype/rgba.go
new file mode 100644
index 00000000..9809ff6a
--- /dev/null
+++ b/internal/integration/customformats/rgbatype/rgba.go
@@ -0,0 +1,39 @@
+// Package rgbatype defines a custom format for RGBA colors.
+package rgbatype
+
+import (
+	"fmt"
+
+	"github.com/go-faster/jx"
+)
+
+type RGBA struct {
+	R, G, B, A uint8
+}
+
+type JSONRGBAEncoding struct{}
+
+func (JSONRGBAEncoding) EncodeJSON(e *jx.Encoder, v RGBA) {
+	var t TextRGBAEncoding
+	e.Str(t.EncodeText(v))
+}
+
+func (JSONRGBAEncoding) DecodeJSON(d *jx.Decoder) (v RGBA, _ error) {
+	s, err := d.Str()
+	if err != nil {
+		return v, err
+	}
+	var t TextRGBAEncoding
+	return t.DecodeText(s)
+}
+
+type TextRGBAEncoding struct{}
+
+func (TextRGBAEncoding) EncodeText(v RGBA) string {
+	return fmt.Sprintf("rgba(%d,%d,%d,%d)", v.R, v.G, v.B, v.A)
+}
+
+func (TextRGBAEncoding) DecodeText(s string) (v RGBA, _ error) {
+	_, err := fmt.Sscanf(s, "rgba(%d,%d,%d,%d)", &v.R, &v.G, &v.B, &v.A)
+	return v, err
+}
diff --git a/internal/integration/generate.go b/internal/integration/generate.go
index 30d27b54..e2d0144e 100644
--- a/internal/integration/generate.go
+++ b/internal/integration/generate.go
@@ -20,6 +20,8 @@ package integration
 //go:generate go run ../../cmd/ogen -v --clean --target test_form             ../../_testdata/positive/form.json
 //go:generate go run ../../cmd/ogen -v --clean --target test_parameters       ../../_testdata/positive/parameters.json
 //
+//go:generate go run ./cmd/customformats ../../_testdata/positive/custom_formats.json test_customformats
+//
 //go:generate go run ../../cmd/ogen -v --clean --target referenced_path_item ../../_testdata/positive/referenced_pathItem.json
 //
 //go:generate go run ../../cmd/ogen -v --clean --generate-tests --target test_allof ../../_testdata/positive/allOf.yml


Test patch:
diff --git a/_testdata/positive/custom_formats.json b/_testdata/positive/custom_formats.json
new file mode 100644
index 00000000..f13d0ad3
--- /dev/null
+++ b/_testdata/positive/custom_formats.json
@@ -0,0 +1,98 @@
+{
+  "openapi": "3.0.3",
+  "info": {
+    "title": "title",
+    "version": "v0.1.0"
+  },
+  "paths": {
+    "/phone": {
+      "get": {
+        "parameters": [
+          {
+            "$ref": "#/components/parameters/Phone"
+          },
+          {
+            "$ref": "#/components/parameters/Color"
+          }
+        ],
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "$ref": "#/components/schemas/User"
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "User info",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/User"
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+  },
+  "components": {
+    "parameters": {
+      "Phone": {
+        "name": "phone",
+        "in": "query",
+        "description": "Phone number",
+        "required": true,
+        "schema": {
+          "type": "string",
+          "format": "phone"
+        }
+      },
+      "Color": {
+        "name": "color",
+        "in": "query",
+        "description": "Color",
+        "schema": {
+          "type": "string",
+          "format": "rgba"
+        }
+      }
+    },
+    "schemas": {
+      "User": {
+        "type": "object",
+        "required": [
+          "id",
+          "phone",
+          "profile_color"
+        ],
+        "properties": {
+          "id": {
+            "type": "integer",
+            "format": "int64"
+          },
+          "phone": {
+            "type": "string",
+            "format": "phone"
+          },
+          "home_phone": {
+            "type": "string",
+            "format": "phone"
+          },
+          "profile_color": {
+            "type": "string",
+            "format": "rgba"
+          },
+          "background_color": {
+            "type": "string",
+            "format": "rgba"
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/gen_test.go b/gen_test.go
index 196b7953..31a9a615 100644
--- a/gen_test.go
+++ b/gen_test.go
@@ -14,7 +14,10 @@ import (
 	"github.com/ogen-go/ogen/gen"
 	"github.com/ogen-go/ogen/gen/genfs"
 	"github.com/ogen-go/ogen/gen/ir"
+	"github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	"github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
 	"github.com/ogen-go/ogen/internal/location"
+	"github.com/ogen-go/ogen/jsonschema"
 	"github.com/ogen-go/ogen/openapi/parser"
 )
 
@@ -37,7 +40,9 @@ func testGenerate(t *testing.T, dir, filename string, data []byte, aliases ctAli
 		File:               location.NewFile(filename, filename, data),
 		Logger:             log,
 	}
-	if filename == "file_reference.yml" { // HACK
+
+	switch filename {
+	case "file_reference.yml": // HACK
 		opt.AllowRemote = true
 		opt.RootURL = &url.URL{
 			Scheme: "file",
@@ -58,7 +63,23 @@ func testGenerate(t *testing.T, dir, filename string, data []byte, aliases ctAli
 				return u.Path, nil
 			},
 		}
+	case "custom_formats.json":
+		opt.CustomFormats = gen.CustomFormatsMap{
+			jsonschema.String: {
+				"phone": gen.CustomFormat[
+					phonetype.Phone,
+					phonetype.JSONPhoneEncoding,
+					phonetype.TextPhoneEncoding,
+				](),
+				"rgba": gen.CustomFormat[
+					rgbatype.RGBA,
+					rgbatype.JSONRGBAEncoding,
+					rgbatype.TextRGBAEncoding,
+				](),
+			},
+		}
 	}
+
 	t.Run("Gen", func(t *testing.T) {
 		defer func() {
 			if rr := recover(); rr != nil {
diff --git a/internal/integration/customformats/phonetype/phone_test.go b/internal/integration/customformats/phonetype/phone_test.go
new file mode 100644
index 00000000..b431f7aa
--- /dev/null
+++ b/internal/integration/customformats/phonetype/phone_test.go
@@ -0,0 +1,48 @@
+package phonetype
+
+import (
+	"fmt"
+	"testing"
+
+	"github.com/go-faster/jx"
+	"github.com/stretchr/testify/require"
+)
+
+func TestPhone(t *testing.T) {
+	for i, tt := range []struct {
+		input   string
+		want    Phone
+		wantErr bool
+	}{
+		{`"+1234567890"`, Phone("+1234567890"), false},
+		{`"+9876543210"`, Phone("+9876543210"), false},
+
+		// Wrong number format.
+		{`"+"`, Phone(""), true},
+		{`"123456789"`, Phone(""), true},
+		{`"+123456789a"`, Phone(""), true},
+		// Wrong JSON type.
+		{`null`, Phone(""), true},
+		{`true`, Phone(""), true},
+		{`0`, Phone(""), true},
+		// Invalid JSON.
+		{`"`, Phone(""), true},
+	} {
+		t.Run(fmt.Sprintf("Test%d", i+1), func(t *testing.T) {
+			a := require.New(t)
+
+			var enc JSONPhoneEncoding
+			v, err := enc.DecodeJSON(jx.DecodeStr(tt.input))
+			if tt.wantErr {
+				a.Error(err)
+				return
+			}
+			a.NoError(err)
+			a.Equal(tt.want, v)
+
+			e := jx.GetEncoder()
+			enc.EncodeJSON(e, tt.want)
+			a.JSONEq(tt.input, e.String())
+		})
+	}
+}
diff --git a/internal/integration/customformats/rgbatype/rgba_test.go b/internal/integration/customformats/rgbatype/rgba_test.go
new file mode 100644
index 00000000..5c0a793f
--- /dev/null
+++ b/internal/integration/customformats/rgbatype/rgba_test.go
@@ -0,0 +1,55 @@
+package rgbatype
+
+import (
+	"fmt"
+	"testing"
+
+	"github.com/go-faster/jx"
+	"github.com/stretchr/testify/require"
+)
+
+func TestRGBA(t *testing.T) {
+	for i, tt := range []struct {
+		input   string
+		want    RGBA
+		wantErr bool
+	}{
+		{`"rgba(1,1,1,1)"`, RGBA{R: 1, G: 1, B: 1, A: 1}, false},
+		{`"rgba(255,0,255,255)"`, RGBA{R: 255, G: 0, B: 255, A: 255}, false},
+
+		// Wrong number format.
+		{`"rgba(1,1,1,-1)"`, RGBA{}, true},
+		{`"rgba(1,1,1,1.0)"`, RGBA{}, true},
+		{`"rgba(1,1,1,256)"`, RGBA{}, true},
+		{`"rgba(1,1,1,a)"`, RGBA{}, true},
+		// Wrong name of the function.
+		{`"rgb(1,1,1,1)"`, RGBA{}, true},
+		// Wrong number of arguments.
+		{`"rgba(1,1,1)"`, RGBA{}, true},
+		// Invalid syntax.
+		{`"rgba(1,1,1,1"`, RGBA{}, true},
+		// Wrong JSON type.
+		{`null`, RGBA{}, true},
+		{`true`, RGBA{}, true},
+		{`0`, RGBA{}, true},
+		// Invalid JSON.
+		{`"`, RGBA{}, true},
+	} {
+		t.Run(fmt.Sprintf("Test%d", i+1), func(t *testing.T) {
+			a := require.New(t)
+
+			var enc JSONRGBAEncoding
+			v, err := enc.DecodeJSON(jx.DecodeStr(tt.input))
+			if tt.wantErr {
+				a.Error(err)
+				return
+			}
+			a.NoError(err)
+			a.Equal(tt.want, v)
+
+			e := jx.GetEncoder()
+			enc.EncodeJSON(e, tt.want)
+			a.JSONEq(tt.input, e.String())
+		})
+	}
+}
diff --git a/internal/integration/customformats_test.go b/internal/integration/customformats_test.go
new file mode 100644
index 00000000..1bd03fd1
--- /dev/null
+++ b/internal/integration/customformats_test.go
@@ -0,0 +1,60 @@
+package integration
+
+import (
+	"context"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+
+	"github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	"github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+	"github.com/ogen-go/ogen/internal/integration/test_customformats"
+)
+
+type testCustomFormats struct{}
+
+func (t testCustomFormats) PhoneGet(ctx context.Context, req *api.User, params api.PhoneGetParams) (*api.User, error) {
+	cpy := *req
+	cpy.HomePhone.SetTo(params.Phone)
+	if v, ok := params.Color.Get(); ok {
+		cpy.BackgroundColor.SetTo(v)
+	}
+	return &cpy, nil
+}
+
+func TestCustomFormats(t *testing.T) {
+	a := require.New(t)
+	ctx := context.Background()
+
+	srv, err := api.NewServer(testCustomFormats{})
+	a.NoError(err)
+
+	s := httptest.NewServer(srv)
+	defer s.Close()
+
+	client, err := api.NewClient(s.URL, api.WithClient(s.Client()))
+	a.NoError(err)
+
+	var (
+		homePhone       = phonetype.Phone("+1234567890")
+		backgroundColor = rgbatype.RGBA{R: 255, G: 0, B: 0, A: 255}
+		u               = &api.User{
+			ID:           10,
+			Phone:        "+1234567890",
+			ProfileColor: rgbatype.RGBA{R: 0, G: 0, B: 0, A: 255},
+		}
+	)
+
+	u2, err := client.PhoneGet(ctx, u, api.PhoneGetParams{
+		Phone: homePhone,
+		Color: api.NewOptRgba(backgroundColor),
+	})
+	a.NoError(err)
+
+	a.Equal(u.ID, u2.ID)
+	a.Equal(u.Phone, u2.Phone)
+	a.Equal(u.ProfileColor, u2.ProfileColor)
+	a.Equal(homePhone, u2.HomePhone.Or(""))
+	a.Equal(backgroundColor, u2.BackgroundColor.Or(rgbatype.RGBA{}))
+}
diff --git a/internal/integration/test_customformats/oas_cfg_gen.go b/internal/integration/test_customformats/oas_cfg_gen.go
new file mode 100644
index 00000000..f6a4159c
--- /dev/null
+++ b/internal/integration/test_customformats/oas_cfg_gen.go
@@ -0,0 +1,293 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"net/http"
+
+	"go.opentelemetry.io/otel"
+	"go.opentelemetry.io/otel/metric"
+	"go.opentelemetry.io/otel/metric/instrument/syncint64"
+	"go.opentelemetry.io/otel/trace"
+
+	ht "github.com/ogen-go/ogen/http"
+	custom0 "github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	custom1 "github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+	"github.com/ogen-go/ogen/middleware"
+	"github.com/ogen-go/ogen/ogenerrors"
+	"github.com/ogen-go/ogen/otelogen"
+)
+
+var (
+	formatPhone = func() (r struct {
+		custom0.JSONPhoneEncoding
+		custom0.TextPhoneEncoding
+	}) {
+		return r
+	}
+	formatRgba = func() (r struct {
+		custom1.JSONRGBAEncoding
+		custom1.TextRGBAEncoding
+	}) {
+		return r
+	}
+)
+var (
+	// Allocate option closure once.
+	clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
+	// Allocate option closure once.
+	serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
+)
+
+type (
+	optionFunc[C any] func(*C)
+	otelOptionFunc    func(*otelConfig)
+)
+
+type otelConfig struct {
+	TracerProvider trace.TracerProvider
+	Tracer         trace.Tracer
+	MeterProvider  metric.MeterProvider
+	Meter          metric.Meter
+}
+
+func (cfg *otelConfig) initOTEL() {
+	if cfg.TracerProvider == nil {
+		cfg.TracerProvider = otel.GetTracerProvider()
+	}
+	if cfg.MeterProvider == nil {
+		cfg.MeterProvider = metric.NewNoopMeterProvider()
+	}
+	cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
+		trace.WithInstrumentationVersion(otelogen.SemVersion()),
+	)
+	cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name)
+}
+
+// ErrorHandler is error handler.
+type ErrorHandler = ogenerrors.ErrorHandler
+
+type serverConfig struct {
+	otelConfig
+	NotFound           http.HandlerFunc
+	MethodNotAllowed   func(w http.ResponseWriter, r *http.Request, allowed string)
+	ErrorHandler       ErrorHandler
+	Prefix             string
+	Middleware         Middleware
+	MaxMultipartMemory int64
+}
+
+// ServerOption is server config option.
+type ServerOption interface {
+	applyServer(*serverConfig)
+}
+
+var _ = []ServerOption{
+	(optionFunc[serverConfig])(nil),
+	(otelOptionFunc)(nil),
+}
+
+func (o optionFunc[C]) applyServer(c *C) {
+	o(c)
+}
+
+func (o otelOptionFunc) applyServer(c *serverConfig) {
+	o(&c.otelConfig)
+}
+
+func newServerConfig(opts ...ServerOption) serverConfig {
+	cfg := serverConfig{
+		NotFound: http.NotFound,
+		MethodNotAllowed: func(w http.ResponseWriter, r *http.Request, allowed string) {
+			w.Header().Set("Allow", allowed)
+			w.WriteHeader(http.StatusMethodNotAllowed)
+		},
+		ErrorHandler:       ogenerrors.DefaultErrorHandler,
+		Middleware:         nil,
+		MaxMultipartMemory: 32 << 20, // 32 MB
+	}
+	for _, opt := range opts {
+		opt.applyServer(&cfg)
+	}
+	cfg.initOTEL()
+	return cfg
+}
+
+type baseServer struct {
+	cfg      serverConfig
+	requests syncint64.Counter
+	errors   syncint64.Counter
+	duration syncint64.Histogram
+}
+
+func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
+	s.cfg.NotFound(w, r)
+}
+
+func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, allowed string) {
+	s.cfg.MethodNotAllowed(w, r, allowed)
+}
+
+func (cfg serverConfig) baseServer() (s baseServer, err error) {
+	s = baseServer{cfg: cfg}
+	if s.requests, err = s.cfg.Meter.SyncInt64().Counter(otelogen.ServerRequestCount); err != nil {
+		return s, err
+	}
+	if s.errors, err = s.cfg.Meter.SyncInt64().Counter(otelogen.ServerErrorsCount); err != nil {
+		return s, err
+	}
+	if s.duration, err = s.cfg.Meter.SyncInt64().Histogram(otelogen.ServerDuration); err != nil {
+		return s, err
+	}
+	return s, nil
+}
+
+type clientConfig struct {
+	otelConfig
+	Client ht.Client
+}
+
+// ClientOption is client config option.
+type ClientOption interface {
+	applyClient(*clientConfig)
+}
+
+var _ = []ClientOption{
+	(optionFunc[clientConfig])(nil),
+	(otelOptionFunc)(nil),
+}
+
+func (o optionFunc[C]) applyClient(c *C) {
+	o(c)
+}
+
+func (o otelOptionFunc) applyClient(c *clientConfig) {
+	o(&c.otelConfig)
+}
+
+func newClientConfig(opts ...ClientOption) clientConfig {
+	cfg := clientConfig{
+		Client: http.DefaultClient,
+	}
+	for _, opt := range opts {
+		opt.applyClient(&cfg)
+	}
+	cfg.initOTEL()
+	return cfg
+}
+
+type baseClient struct {
+	cfg      clientConfig
+	requests syncint64.Counter
+	errors   syncint64.Counter
+	duration syncint64.Histogram
+}
+
+func (cfg clientConfig) baseClient() (c baseClient, err error) {
+	c = baseClient{cfg: cfg}
+	if c.requests, err = c.cfg.Meter.SyncInt64().Counter(otelogen.ClientRequestCount); err != nil {
+		return c, err
+	}
+	if c.errors, err = c.cfg.Meter.SyncInt64().Counter(otelogen.ClientErrorsCount); err != nil {
+		return c, err
+	}
+	if c.duration, err = c.cfg.Meter.SyncInt64().Histogram(otelogen.ClientDuration); err != nil {
+		return c, err
+	}
+	return c, nil
+}
+
+// Option is config option.
+type Option interface {
+	ServerOption
+	ClientOption
+}
+
+// WithTracerProvider specifies a tracer provider to use for creating a tracer.
+//
+// If none is specified, the global provider is used.
+func WithTracerProvider(provider trace.TracerProvider) Option {
+	return otelOptionFunc(func(cfg *otelConfig) {
+		if provider != nil {
+			cfg.TracerProvider = provider
+		}
+	})
+}
+
+// WithMeterProvider specifies a meter provider to use for creating a meter.
+//
+// If none is specified, the metric.NewNoopMeterProvider is used.
+func WithMeterProvider(provider metric.MeterProvider) Option {
+	return otelOptionFunc(func(cfg *otelConfig) {
+		if provider != nil {
+			cfg.MeterProvider = provider
+		}
+	})
+}
+
+// WithClient specifies http client to use.
+func WithClient(client ht.Client) ClientOption {
+	return optionFunc[clientConfig](func(cfg *clientConfig) {
+		if client != nil {
+			cfg.Client = client
+		}
+	})
+}
+
+// WithNotFound specifies Not Found handler to use.
+func WithNotFound(notFound http.HandlerFunc) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		if notFound != nil {
+			cfg.NotFound = notFound
+		}
+	})
+}
+
+// WithMethodNotAllowed specifies Method Not Allowed handler to use.
+func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		if methodNotAllowed != nil {
+			cfg.MethodNotAllowed = methodNotAllowed
+		}
+	})
+}
+
+// WithErrorHandler specifies error handler to use.
+func WithErrorHandler(h ErrorHandler) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		if h != nil {
+			cfg.ErrorHandler = h
+		}
+	})
+}
+
+// WithPathPrefix specifies server path prefix.
+func WithPathPrefix(prefix string) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		cfg.Prefix = prefix
+	})
+}
+
+// WithMiddleware specifies middlewares to use.
+func WithMiddleware(m ...Middleware) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		switch len(m) {
+		case 0:
+			cfg.Middleware = nil
+		case 1:
+			cfg.Middleware = m[0]
+		default:
+			cfg.Middleware = middleware.ChainMiddlewares(m...)
+		}
+	})
+}
+
+// WithMaxMultipartMemory specifies limit of memory for storing file parts.
+// File parts which can't be stored in memory will be stored on disk in temporary files.
+func WithMaxMultipartMemory(max int64) ServerOption {
+	return optionFunc[serverConfig](func(cfg *serverConfig) {
+		if max > 0 {
+			cfg.MaxMultipartMemory = max
+		}
+	})
+}
diff --git a/internal/integration/test_customformats/oas_client_gen.go b/internal/integration/test_customformats/oas_client_gen.go
new file mode 100644
index 00000000..a9251c20
--- /dev/null
+++ b/internal/integration/test_customformats/oas_client_gen.go
@@ -0,0 +1,158 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"context"
+	"net/url"
+	"time"
+
+	"github.com/go-faster/errors"
+	"go.opentelemetry.io/otel/attribute"
+	"go.opentelemetry.io/otel/codes"
+
+	ht "github.com/ogen-go/ogen/http"
+	"github.com/ogen-go/ogen/uri"
+)
+
+var _ Handler = struct {
+	*Client
+}{}
+
+// Client implements OAS client.
+type Client struct {
+	serverURL *url.URL
+	baseClient
+}
+
+// NewClient initializes new Client defined by OAS.
+func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
+	u, err := url.Parse(serverURL)
+	if err != nil {
+		return nil, err
+	}
+	c, err := newClientConfig(opts...).baseClient()
+	if err != nil {
+		return nil, err
+	}
+	return &Client{
+		serverURL:  u,
+		baseClient: c,
+	}, nil
+}
+
+type serverURLKey struct{}
+
+// WithServerURL sets context key to override server URL.
+func WithServerURL(ctx context.Context, u *url.URL) context.Context {
+	return context.WithValue(ctx, serverURLKey{}, u)
+}
+
+func (c *Client) requestURL(ctx context.Context) *url.URL {
+	u, ok := ctx.Value(serverURLKey{}).(*url.URL)
+	if !ok {
+		return c.serverURL
+	}
+	return u
+}
+
+// PhoneGet invokes GET /phone operation.
+//
+// GET /phone
+func (c *Client) PhoneGet(ctx context.Context, request *User, params PhoneGetParams) (*User, error) {
+	res, err := c.sendPhoneGet(ctx, request, params)
+	_ = res
+	return res, err
+}
+
+func (c *Client) sendPhoneGet(ctx context.Context, request *User, params PhoneGetParams) (res *User, err error) {
+	var otelAttrs []attribute.KeyValue
+
+	// Run stopwatch.
+	startTime := time.Now()
+	defer func() {
+		elapsedDuration := time.Since(startTime)
+		c.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
+	}()
+
+	// Increment request counter.
+	c.requests.Add(ctx, 1, otelAttrs...)
+
+	// Start a span for this request.
+	ctx, span := c.cfg.Tracer.Start(ctx, "PhoneGet",
+		clientSpanKind,
+	)
+	// Track stage for error reporting.
+	var stage string
+	defer func() {
+		if err != nil {
+			span.RecordError(err)
+			span.SetStatus(codes.Error, stage)
+			c.errors.Add(ctx, 1, otelAttrs...)
+		}
+		span.End()
+	}()
+
+	stage = "BuildURL"
+	u := uri.Clone(c.requestURL(ctx))
+	u.Path += "/phone"
+
+	stage = "EncodeQueryParams"
+	q := uri.NewQueryEncoder()
+	{
+		// Encode "phone" parameter.
+		cfg := uri.QueryParameterEncodingConfig{
+			Name:    "phone",
+			Style:   uri.QueryStyleForm,
+			Explode: true,
+		}
+
+		if err := q.EncodeParam(cfg, func(e uri.Encoder) error {
+			return e.EncodeValue(formatPhone().EncodeText(params.Phone))
+		}); err != nil {
+			return res, errors.Wrap(err, "encode query")
+		}
+	}
+	{
+		// Encode "color" parameter.
+		cfg := uri.QueryParameterEncodingConfig{
+			Name:    "color",
+			Style:   uri.QueryStyleForm,
+			Explode: true,
+		}
+
+		if err := q.EncodeParam(cfg, func(e uri.Encoder) error {
+			if val, ok := params.Color.Get(); ok {
+				return e.EncodeValue(formatRgba().EncodeText(val))
+			}
+			return nil
+		}); err != nil {
+			return res, errors.Wrap(err, "encode query")
+		}
+	}
+	u.RawQuery = q.Values().Encode()
+
+	stage = "EncodeRequest"
+	r, err := ht.NewRequest(ctx, "GET", u, nil)
+	if err != nil {
+		return res, errors.Wrap(err, "create request")
+	}
+	if err := encodePhoneGetRequest(request, r); err != nil {
+		return res, errors.Wrap(err, "encode request")
+	}
+
+	stage = "SendRequest"
+	resp, err := c.cfg.Client.Do(r)
+	if err != nil {
+		return res, errors.Wrap(err, "do request")
+	}
+	defer resp.Body.Close()
+
+	stage = "DecodeResponse"
+	result, err := decodePhoneGetResponse(resp)
+	if err != nil {
+		return res, errors.Wrap(err, "decode response")
+	}
+
+	return result, nil
+}
diff --git a/internal/integration/test_customformats/oas_handlers_gen.go b/internal/integration/test_customformats/oas_handlers_gen.go
new file mode 100644
index 00000000..607aad1c
--- /dev/null
+++ b/internal/integration/test_customformats/oas_handlers_gen.go
@@ -0,0 +1,129 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"context"
+	"net/http"
+	"time"
+
+	"go.opentelemetry.io/otel/attribute"
+	"go.opentelemetry.io/otel/codes"
+
+	"github.com/ogen-go/ogen/middleware"
+	"github.com/ogen-go/ogen/ogenerrors"
+)
+
+// handlePhoneGetRequest handles GET /phone operation.
+//
+// GET /phone
+func (s *Server) handlePhoneGetRequest(args [0]string, w http.ResponseWriter, r *http.Request) {
+	var otelAttrs []attribute.KeyValue
+
+	// Start a span for this request.
+	ctx, span := s.cfg.Tracer.Start(r.Context(), "PhoneGet",
+		serverSpanKind,
+	)
+	defer span.End()
+
+	// Run stopwatch.
+	startTime := time.Now()
+	defer func() {
+		elapsedDuration := time.Since(startTime)
+		s.duration.Record(ctx, elapsedDuration.Microseconds(), otelAttrs...)
+	}()
+
+	// Increment request counter.
+	s.requests.Add(ctx, 1, otelAttrs...)
+
+	var (
+		recordError = func(stage string, err error) {
+			span.RecordError(err)
+			span.SetStatus(codes.Error, stage)
+			s.errors.Add(ctx, 1, otelAttrs...)
+		}
+		err          error
+		opErrContext = ogenerrors.OperationContext{
+			Name: "PhoneGet",
+			ID:   "",
+		}
+	)
+	params, err := decodePhoneGetParams(args, r)
+	if err != nil {
+		err = &ogenerrors.DecodeParamsError{
+			OperationContext: opErrContext,
+			Err:              err,
+		}
+		recordError("DecodeParams", err)
+		s.cfg.ErrorHandler(ctx, w, r, err)
+		return
+	}
+	request, close, err := s.decodePhoneGetRequest(r)
+	if err != nil {
+		err = &ogenerrors.DecodeRequestError{
+			OperationContext: opErrContext,
+			Err:              err,
+		}
+		recordError("DecodeRequest", err)
+		s.cfg.ErrorHandler(ctx, w, r, err)
+		return
+	}
+	defer func() {
+		if err := close(); err != nil {
+			recordError("CloseRequest", err)
+		}
+	}()
+
+	var response *User
+	if m := s.cfg.Middleware; m != nil {
+		mreq := middleware.Request{
+			Context:       ctx,
+			OperationName: "PhoneGet",
+			OperationID:   "",
+			Body:          request,
+			Params: middleware.Parameters{
+				{
+					Name: "phone",
+					In:   "query",
+				}: params.Phone,
+				{
+					Name: "color",
+					In:   "query",
+				}: params.Color,
+			},
+			Raw: r,
+		}
+
+		type (
+			Request  = *User
+			Params   = PhoneGetParams
+			Response = *User
+		)
+		response, err = middleware.HookMiddleware[
+			Request,
+			Params,
+			Response,
+		](
+			m,
+			mreq,
+			unpackPhoneGetParams,
+			func(ctx context.Context, request Request, params Params) (response Response, err error) {
+				response, err = s.h.PhoneGet(ctx, request, params)
+				return response, err
+			},
+		)
+	} else {
+		response, err = s.h.PhoneGet(ctx, request, params)
+	}
+	if err != nil {
+		recordError("Internal", err)
+		s.cfg.ErrorHandler(ctx, w, r, err)
+		return
+	}
+
+	if err := encodePhoneGetResponse(response, w, span); err != nil {
+		recordError("EncodeResponse", err)
+		s.cfg.ErrorHandler(ctx, w, r, err)
+		return
+	}
+}
diff --git a/internal/integration/test_customformats/oas_json_gen.go b/internal/integration/test_customformats/oas_json_gen.go
new file mode 100644
index 00000000..b1c08f70
--- /dev/null
+++ b/internal/integration/test_customformats/oas_json_gen.go
@@ -0,0 +1,252 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"math/bits"
+	"strconv"
+
+	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
+
+	custom0 "github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	custom1 "github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+	"github.com/ogen-go/ogen/validate"
+)
+
+// Encode encodes custom0.Phone as json.
+func (o OptPhone) Encode(e *jx.Encoder, format func(*jx.Encoder, custom0.Phone)) {
+	if !o.Set {
+		return
+	}
+	formatPhone().EncodeJSON(e, o.Value)
+}
+
+// Decode decodes custom0.Phone from json.
+func (o *OptPhone) Decode(d *jx.Decoder, format func(*jx.Decoder) (custom0.Phone, error)) error {
+	if o == nil {
+		return errors.New("invalid: unable to decode OptPhone to nil")
+	}
+	o.Set = true
+	v, err := formatPhone().DecodeJSON(d)
+	if err != nil {
+		return err
+	}
+	o.Value = v
+	return nil
+}
+
+// MarshalJSON implements stdjson.Marshaler.
+func (s OptPhone) MarshalJSON() ([]byte, error) {
+	e := jx.Encoder{}
+	s.Encode(&e, formatPhone().EncodeJSON)
+	return e.Bytes(), nil
+}
+
+// UnmarshalJSON implements stdjson.Unmarshaler.
+func (s *OptPhone) UnmarshalJSON(data []byte) error {
+	d := jx.DecodeBytes(data)
+	return s.Decode(d, formatPhone().DecodeJSON)
+}
+
+// Encode encodes custom1.RGBA as json.
+func (o OptRgba) Encode(e *jx.Encoder, format func(*jx.Encoder, custom1.RGBA)) {
+	if !o.Set {
+		return
+	}
+	formatRgba().EncodeJSON(e, o.Value)
+}
+
+// Decode decodes custom1.RGBA from json.
+func (o *OptRgba) Decode(d *jx.Decoder, format func(*jx.Decoder) (custom1.RGBA, error)) error {
+	if o == nil {
+		return errors.New("invalid: unable to decode OptRgba to nil")
+	}
+	o.Set = true
+	v, err := formatRgba().DecodeJSON(d)
+	if err != nil {
+		return err
+	}
+	o.Value = v
+	return nil
+}
+
+// MarshalJSON implements stdjson.Marshaler.
+func (s OptRgba) MarshalJSON() ([]byte, error) {
+	e := jx.Encoder{}
+	s.Encode(&e, formatRgba().EncodeJSON)
+	return e.Bytes(), nil
+}
+
+// UnmarshalJSON implements stdjson.Unmarshaler.
+func (s *OptRgba) UnmarshalJSON(data []byte) error {
+	d := jx.DecodeBytes(data)
+	return s.Decode(d, formatRgba().DecodeJSON)
+}
+
+// Encode implements json.Marshaler.
+func (s *User) Encode(e *jx.Encoder) {
+	e.ObjStart()
+	s.encodeFields(e)
+	e.ObjEnd()
+}
+
+// encodeFields encodes fields.
+func (s *User) encodeFields(e *jx.Encoder) {
+	{
+
+		e.FieldStart("id")
+		e.Int64(s.ID)
+	}
+	{
+
+		e.FieldStart("phone")
+		formatPhone().EncodeJSON(e, s.Phone)
+	}
+	{
+		if s.HomePhone.Set {
+			e.FieldStart("home_phone")
+			s.HomePhone.Encode(e, formatPhone().EncodeJSON)
+		}
+	}
+	{
+
+		e.FieldStart("profile_color")
+		formatRgba().EncodeJSON(e, s.ProfileColor)
+	}
+	{
+		if s.BackgroundColor.Set {
+			e.FieldStart("background_color")
+			s.BackgroundColor.Encode(e, formatRgba().EncodeJSON)
+		}
+	}
+}
+
+var jsonFieldsNameOfUser = [5]string{
+	0: "id",
+	1: "phone",
+	2: "home_phone",
+	3: "profile_color",
+	4: "background_color",
+}
+
+// Decode decodes User from json.
+func (s *User) Decode(d *jx.Decoder) error {
+	if s == nil {
+		return errors.New("invalid: unable to decode User to nil")
+	}
+	var requiredBitSet [1]uint8
+
+	if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
+		switch string(k) {
+		case "id":
+			requiredBitSet[0] |= 1 << 0
+			if err := func() error {
+				v, err := d.Int64()
+				s.ID = int64(v)
+				if err != nil {
+					return err
+				}
+				return nil
+			}(); err != nil {
+				return errors.Wrap(err, "decode field \"id\"")
+			}
+		case "phone":
+			requiredBitSet[0] |= 1 << 1
+			if err := func() error {
+				v, err := formatPhone().DecodeJSON(d)
+				s.Phone = v
+				if err != nil {
+					return err
+				}
+				return nil
+			}(); err != nil {
+				return errors.Wrap(err, "decode field \"phone\"")
+			}
+		case "home_phone":
+			if err := func() error {
+				s.HomePhone.Reset()
+				if err := s.HomePhone.Decode(d, formatPhone().DecodeJSON); err != nil {
+					return err
+				}
+				return nil
+			}(); err != nil {
+				return errors.Wrap(err, "decode field \"home_phone\"")
+			}
+		case "profile_color":
+			requiredBitSet[0] |= 1 << 3
+			if err := func() error {
+				v, err := formatRgba().DecodeJSON(d)
+				s.ProfileColor = v
+				if err != nil {
+					return err
+				}
+				return nil
+			}(); err != nil {
+				return errors.Wrap(err, "decode field \"profile_color\"")
+			}
+		case "background_color":
+			if err := func() error {
+				s.BackgroundColor.Reset()
+				if err := s.BackgroundColor.Decode(d, formatRgba().DecodeJSON); err != nil {
+					return err
+				}
+				return nil
+			}(); err != nil {
+				return errors.Wrap(err, "decode field \"background_color\"")
+			}
+		default:
+			return d.Skip()
+		}
+		return nil
+	}); err != nil {
+		return errors.Wrap(err, "decode User")
+	}
+	// Validate required fields.
+	var failures []validate.FieldError
+	for i, mask := range [1]uint8{
+		0b00001011,
+	} {
+		if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
+			// Mask only required fields and check equality to mask using XOR.
+			//
+			// If XOR result is not zero, result is not equal to expected, so some fields are missed.
+			// Bits of fields which would be set are actually bits of missed fields.
+			missed := bits.OnesCount8(result)
+			for bitN := 0; bitN < missed; bitN++ {
+				bitIdx := bits.TrailingZeros8(result)
+				fieldIdx := i*8 + bitIdx
+				var name string
+				if fieldIdx < len(jsonFieldsNameOfUser) {
+					name = jsonFieldsNameOfUser[fieldIdx]
+				} else {
+					name = strconv.Itoa(fieldIdx)
+				}
+				failures = append(failures, validate.FieldError{
+					Name:  name,
+					Error: validate.ErrFieldRequired,
+				})
+				// Reset bit.
+				result &^= 1 << bitIdx
+			}
+		}
+	}
+	if len(failures) > 0 {
+		return &validate.Error{Fields: failures}
+	}
+
+	return nil
+}
+
+// MarshalJSON implements stdjson.Marshaler.
+func (s *User) MarshalJSON() ([]byte, error) {
+	e := jx.Encoder{}
+	s.Encode(&e)
+	return e.Bytes(), nil
+}
+
+// UnmarshalJSON implements stdjson.Unmarshaler.
+func (s *User) UnmarshalJSON(data []byte) error {
+	d := jx.DecodeBytes(data)
+	return s.Decode(d)
+}
diff --git a/internal/integration/test_customformats/oas_middleware_gen.go b/internal/integration/test_customformats/oas_middleware_gen.go
new file mode 100644
index 00000000..6f58a1a7
--- /dev/null
+++ b/internal/integration/test_customformats/oas_middleware_gen.go
@@ -0,0 +1,10 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"github.com/ogen-go/ogen/middleware"
+)
+
+// Middleware is middleware type.
+type Middleware = middleware.Middleware
diff --git a/internal/integration/test_customformats/oas_parameters_gen.go b/internal/integration/test_customformats/oas_parameters_gen.go
new file mode 100644
index 00000000..48f950db
--- /dev/null
+++ b/internal/integration/test_customformats/oas_parameters_gen.go
@@ -0,0 +1,124 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"net/http"
+
+	custom0 "github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	custom1 "github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+	"github.com/ogen-go/ogen/middleware"
+	"github.com/ogen-go/ogen/ogenerrors"
+	"github.com/ogen-go/ogen/uri"
+	"github.com/ogen-go/ogen/validate"
+)
+
+// PhoneGetParams is parameters of GET /phone operation.
+type PhoneGetParams struct {
+	// Phone number.
+	Phone custom0.Phone
+	// Color.
+	Color OptRgba
+}
+
+func unpackPhoneGetParams(packed middleware.Parameters) (params PhoneGetParams) {
+	{
+		key := middleware.ParameterKey{
+			Name: "phone",
+			In:   "query",
+		}
+		params.Phone = packed[key].(custom0.Phone)
+	}
+	{
+		key := middleware.ParameterKey{
+			Name: "color",
+			In:   "query",
+		}
+		if v, ok := packed[key]; ok {
+			params.Color = v.(OptRgba)
+		}
+	}
+	return params
+}
+
+func decodePhoneGetParams(args [0]string, r *http.Request) (params PhoneGetParams, _ error) {
+	q := uri.NewQueryDecoder(r.URL.Query())
+	// Decode query: phone.
+	if err := func() error {
+		cfg := uri.QueryParameterDecodingConfig{
+			Name:    "phone",
+			Style:   uri.QueryStyleForm,
+			Explode: true,
+		}
+
+		if err := q.HasParam(cfg); err == nil {
+			if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
+				val, err := d.DecodeValue()
+				if err != nil {
+					return err
+				}
+
+				c, err := formatPhone().DecodeText(val)
+				if err != nil {
+					return err
+				}
+
+				params.Phone = c
+				return nil
+			}); err != nil {
+				return err
+			}
+		} else {
+			return validate.ErrFieldRequired
+		}
+		return nil
+	}(); err != nil {
+		return params, &ogenerrors.DecodeParamError{
+			Name: "phone",
+			In:   "query",
+			Err:  err,
+		}
+	}
+	// Decode query: color.
+	if err := func() error {
+		cfg := uri.QueryParameterDecodingConfig{
+			Name:    "color",
+			Style:   uri.QueryStyleForm,
+			Explode: true,
+		}
+
+		if err := q.HasParam(cfg); err == nil {
+			if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
+				var paramsDotColorVal custom1.RGBA
+				if err := func() error {
+					val, err := d.DecodeValue()
+					if err != nil {
+						return err
+					}
+
+					c, err := formatRgba().DecodeText(val)
+					if err != nil {
+						return err
+					}
+
+					paramsDotColorVal = c
+					return nil
+				}(); err != nil {
+					return err
+				}
+				params.Color.SetTo(paramsDotColorVal)
+				return nil
+			}); err != nil {
+				return err
+			}
+		}
+		return nil
+	}(); err != nil {
+		return params, &ogenerrors.DecodeParamError{
+			Name: "color",
+			In:   "query",
+			Err:  err,
+		}
+	}
+	return params, nil
+}
diff --git a/internal/integration/test_customformats/oas_request_decoders_gen.go b/internal/integration/test_customformats/oas_request_decoders_gen.go
new file mode 100644
index 00000000..fb414e57
--- /dev/null
+++ b/internal/integration/test_customformats/oas_request_decoders_gen.go
@@ -0,0 +1,79 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"io"
+	"mime"
+	"net/http"
+
+	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
+	"go.uber.org/multierr"
+
+	"github.com/ogen-go/ogen/ogenerrors"
+	"github.com/ogen-go/ogen/validate"
+)
+
+func (s *Server) decodePhoneGetRequest(r *http.Request) (
+	req *User,
+	close func() error,
+	rerr error,
+) {
+	var closers []func() error
+	close = func() error {
+		var merr error
+		// Close in reverse order, to match defer behavior.
+		for i := len(closers) - 1; i >= 0; i-- {
+			c := closers[i]
+			merr = multierr.Append(merr, c())
+		}
+		return merr
+	}
+	defer func() {
+		if rerr != nil {
+			rerr = multierr.Append(rerr, close())
+		}
+	}()
+	ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+	if err != nil {
+		return req, close, errors.Wrap(err, "parse media type")
+	}
+	switch {
+	case ct == "application/json":
+		if r.ContentLength == 0 {
+			return req, close, validate.ErrBodyRequired
+		}
+
+		var request User
+		buf, err := io.ReadAll(r.Body)
+		if err != nil {
+			return req, close, err
+		}
+
+		if len(buf) == 0 {
+			return req, close, validate.ErrBodyRequired
+		}
+
+		d := jx.DecodeBytes(buf)
+		if err := func() error {
+			if err := request.Decode(d); err != nil {
+				return err
+			}
+			if err := d.Skip(); err != io.EOF {
+				return errors.New("unexpected trailing data")
+			}
+			return nil
+		}(); err != nil {
+			err = &ogenerrors.DecodeBodyError{
+				ContentType: ct,
+				Body:        buf,
+				Err:         err,
+			}
+			return req, close, err
+		}
+		return &request, close, nil
+	default:
+		return req, close, validate.InvalidContentType(ct)
+	}
+}
diff --git a/internal/integration/test_customformats/oas_request_encoders_gen.go b/internal/integration/test_customformats/oas_request_encoders_gen.go
new file mode 100644
index 00000000..3cc38849
--- /dev/null
+++ b/internal/integration/test_customformats/oas_request_encoders_gen.go
@@ -0,0 +1,26 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"bytes"
+	"net/http"
+
+	"github.com/go-faster/jx"
+
+	ht "github.com/ogen-go/ogen/http"
+)
+
+func encodePhoneGetRequest(
+	req *User,
+	r *http.Request,
+) error {
+	const contentType = "application/json"
+	e := jx.GetEncoder()
+	{
+		req.Encode(e)
+	}
+	encoded := e.Bytes()
+	ht.SetBody(r, bytes.NewReader(encoded), contentType)
+	return nil
+}
diff --git a/internal/integration/test_customformats/oas_response_decoders_gen.go b/internal/integration/test_customformats/oas_response_decoders_gen.go
new file mode 100644
index 00000000..da3613dc
--- /dev/null
+++ b/internal/integration/test_customformats/oas_response_decoders_gen.go
@@ -0,0 +1,56 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"io"
+	"mime"
+	"net/http"
+
+	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
+
+	"github.com/ogen-go/ogen/ogenerrors"
+	"github.com/ogen-go/ogen/validate"
+)
+
+func decodePhoneGetResponse(resp *http.Response) (res *User, err error) {
+	switch resp.StatusCode {
+	case 200:
+		// Code 200.
+		ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
+		if err != nil {
+			return res, errors.Wrap(err, "parse media type")
+		}
+		switch {
+		case ct == "application/json":
+			buf, err := io.ReadAll(resp.Body)
+			if err != nil {
+				return res, err
+			}
+
+			d := jx.DecodeBytes(buf)
+			var response User
+			if err := func() error {
+				if err := response.Decode(d); err != nil {
+					return err
+				}
+				if err := d.Skip(); err != io.EOF {
+					return errors.New("unexpected trailing data")
+				}
+				return nil
+			}(); err != nil {
+				err = &ogenerrors.DecodeBodyError{
+					ContentType: ct,
+					Body:        buf,
+					Err:         err,
+				}
+				return res, err
+			}
+			return &response, nil
+		default:
+			return res, validate.InvalidContentType(ct)
+		}
+	}
+	return res, validate.UnexpectedStatusCode(resp.StatusCode)
+}
diff --git a/internal/integration/test_customformats/oas_response_encoders_gen.go b/internal/integration/test_customformats/oas_response_encoders_gen.go
new file mode 100644
index 00000000..a3aafa72
--- /dev/null
+++ b/internal/integration/test_customformats/oas_response_encoders_gen.go
@@ -0,0 +1,25 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"net/http"
+
+	"github.com/go-faster/errors"
+	"github.com/go-faster/jx"
+	"go.opentelemetry.io/otel/codes"
+	"go.opentelemetry.io/otel/trace"
+)
+
+func encodePhoneGetResponse(response *User, w http.ResponseWriter, span trace.Span) error {
+	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(200)
+	span.SetStatus(codes.Ok, http.StatusText(200))
+
+	e := jx.GetEncoder()
+	response.Encode(e)
+	if _, err := e.WriteTo(w); err != nil {
+		return errors.Wrap(err, "write")
+	}
+	return nil
+}
diff --git a/internal/integration/test_customformats/oas_router_gen.go b/internal/integration/test_customformats/oas_router_gen.go
new file mode 100644
index 00000000..8109c363
--- /dev/null
+++ b/internal/integration/test_customformats/oas_router_gen.go
@@ -0,0 +1,148 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"net/http"
+	"net/url"
+	"strings"
+
+	"github.com/ogen-go/ogen/uri"
+)
+
+// ServeHTTP serves http request as defined by OpenAPI v3 specification,
+// calling handler that matches the path or returning not found error.
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	elem := r.URL.Path
+	if rawPath := r.URL.RawPath; rawPath != "" {
+		if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
+			elem = normalized
+		}
+	}
+	if prefix := s.cfg.Prefix; len(prefix) > 0 {
+		if strings.HasPrefix(elem, prefix) {
+			// Cut prefix from the path.
+			elem = strings.TrimPrefix(elem, prefix)
+		} else {
+			// Prefix doesn't match.
+			s.notFound(w, r)
+			return
+		}
+	}
+	if len(elem) == 0 {
+		s.notFound(w, r)
+		return
+	}
+
+	// Static code generated router with unwrapped path search.
+	switch {
+	default:
+		if len(elem) == 0 {
+			break
+		}
+		switch elem[0] {
+		case '/': // Prefix: "/phone"
+			if l := len("/phone"); len(elem) >= l && elem[0:l] == "/phone" {
+				elem = elem[l:]
+			} else {
+				break
+			}
+
+			if len(elem) == 0 {
+				// Leaf node.
+				switch r.Method {
+				case "GET":
+					s.handlePhoneGetRequest([0]string{}, w, r)
+				default:
+					s.notAllowed(w, r, "GET")
+				}
+
+				return
+			}
+		}
+	}
+	s.notFound(w, r)
+}
+
+// Route is route object.
+type Route struct {
+	name        string
+	operationID string
+	count       int
+	args        [0]string
+}
+
+// Name returns ogen operation name.
+//
+// It is guaranteed to be unique and not empty.
+func (r Route) Name() string {
+	return r.name
+}
+
+// OperationID returns OpenAPI operationId.
+func (r Route) OperationID() string {
+	return r.operationID
+}
+
+// Args returns parsed arguments.
+func (r Route) Args() []string {
+	return r.args[:r.count]
+}
+
+// FindRoute finds Route for given method and path.
+//
+// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
+func (s *Server) FindRoute(method, path string) (Route, bool) {
+	return s.FindPath(method, &url.URL{Path: path})
+}
+
+// FindPath finds Route for given method and URL.
+func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
+	var (
+		elem = u.Path
+		args = r.args
+	)
+	if rawPath := u.RawPath; rawPath != "" {
+		if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
+			elem = normalized
+		}
+		defer func() {
+			for i, arg := range r.args[:r.count] {
+				if unescaped, err := url.PathUnescape(arg); err == nil {
+					r.args[i] = unescaped
+				}
+			}
+		}()
+	}
+
+	// Static code generated router with unwrapped path search.
+	switch {
+	default:
+		if len(elem) == 0 {
+			break
+		}
+		switch elem[0] {
+		case '/': // Prefix: "/phone"
+			if l := len("/phone"); len(elem) >= l && elem[0:l] == "/phone" {
+				elem = elem[l:]
+			} else {
+				break
+			}
+
+			if len(elem) == 0 {
+				switch method {
+				case "GET":
+					// Leaf: PhoneGet
+					r.name = "PhoneGet"
+					r.operationID = ""
+					r.args = args
+					r.count = 0
+					return r, true
+				default:
+					return
+				}
+			}
+		}
+	}
+	return r, false
+}
diff --git a/internal/integration/test_customformats/oas_schemas_gen.go b/internal/integration/test_customformats/oas_schemas_gen.go
new file mode 100644
index 00000000..eaa83a92
--- /dev/null
+++ b/internal/integration/test_customformats/oas_schemas_gen.go
@@ -0,0 +1,159 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	custom0 "github.com/ogen-go/ogen/internal/integration/customformats/phonetype"
+	custom1 "github.com/ogen-go/ogen/internal/integration/customformats/rgbatype"
+)
+
+// NewOptPhone returns new OptPhone with value set to v.
+func NewOptPhone(v custom0.Phone) OptPhone {
+	return OptPhone{
+		Value: v,
+		Set:   true,
+	}
+}
+
+// OptPhone is optional custom0.Phone.
+type OptPhone struct {
+	Value custom0.Phone
+	Set   bool
+}
+
+// IsSet returns true if OptPhone was set.
+func (o OptPhone) IsSet() bool { return o.Set }
+
+// Reset unsets value.
+func (o *OptPhone) Reset() {
+	var v custom0.Phone
+	o.Value = v
+	o.Set = false
+}
+
+// SetTo sets value to v.
+func (o *OptPhone) SetTo(v custom0.Phone) {
+	o.Set = true
+	o.Value = v
+}
+
+// Get returns value and boolean that denotes whether value was set.
+func (o OptPhone) Get() (v custom0.Phone, ok bool) {
+	if !o.Set {
+		return v, false
+	}
+	return o.Value, true
+}
+
+// Or returns value if set, or given parameter if does not.
+func (o OptPhone) Or(d custom0.Phone) custom0.Phone {
+	if v, ok := o.Get(); ok {
+		return v
+	}
+	return d
+}
+
+// NewOptRgba returns new OptRgba with value set to v.
+func NewOptRgba(v custom1.RGBA) OptRgba {
+	return OptRgba{
+		Value: v,
+		Set:   true,
+	}
+}
+
+// OptRgba is optional custom1.RGBA.
+type OptRgba struct {
+	Value custom1.RGBA
+	Set   bool
+}
+
+// IsSet returns true if OptRgba was set.
+func (o OptRgba) IsSet() bool { return o.Set }
+
+// Reset unsets value.
+func (o *OptRgba) Reset() {
+	var v custom1.RGBA
+	o.Value = v
+	o.Set = false
+}
+
+// SetTo sets value to v.
+func (o *OptRgba) SetTo(v custom1.RGBA) {
+	o.Set = true
+	o.Value = v
+}
+
+// Get returns value and boolean that denotes whether value was set.
+func (o OptRgba) Get() (v custom1.RGBA, ok bool) {
+	if !o.Set {
+		return v, false
+	}
+	return o.Value, true
+}
+
+// Or returns value if set, or given parameter if does not.
+func (o OptRgba) Or(d custom1.RGBA) custom1.RGBA {
+	if v, ok := o.Get(); ok {
+		return v
+	}
+	return d
+}
+
+// Ref: #/components/schemas/User
+type User struct {
+	ID              int64         `json:"id"`
+	Phone           custom0.Phone `json:"phone"`
+	HomePhone       OptPhone      `json:"home_phone"`
+	ProfileColor    custom1.RGBA  `json:"profile_color"`
+	BackgroundColor OptRgba       `json:"background_color"`
+}
+
+// GetID returns the value of ID.
+func (s *User) GetID() int64 {
+	return s.ID
+}
+
+// GetPhone returns the value of Phone.
+func (s *User) GetPhone() custom0.Phone {
+	return s.Phone
+}
+
+// GetHomePhone returns the value of HomePhone.
+func (s *User) GetHomePhone() OptPhone {
+	return s.HomePhone
+}
+
+// GetProfileColor returns the value of ProfileColor.
+func (s *User) GetProfileColor() custom1.RGBA {
+	return s.ProfileColor
+}
+
+// GetBackgroundColor returns the value of BackgroundColor.
+func (s *User) GetBackgroundColor() OptRgba {
+	return s.BackgroundColor
+}
+
+// SetID sets the value of ID.
+func (s *User) SetID(val int64) {
+	s.ID = val
+}
+
+// SetPhone sets the value of Phone.
+func (s *User) SetPhone(val custom0.Phone) {
+	s.Phone = val
+}
+
+// SetHomePhone sets the value of HomePhone.
+func (s *User) SetHomePhone(val OptPhone) {
+	s.HomePhone = val
+}
+
+// SetProfileColor sets the value of ProfileColor.
+func (s *User) SetProfileColor(val custom1.RGBA) {
+	s.ProfileColor = val
+}
+
+// SetBackgroundColor sets the value of BackgroundColor.
+func (s *User) SetBackgroundColor(val OptRgba) {
+	s.BackgroundColor = val
+}
diff --git a/internal/integration/test_customformats/oas_server_gen.go b/internal/integration/test_customformats/oas_server_gen.go
new file mode 100644
index 00000000..a79255db
--- /dev/null
+++ b/internal/integration/test_customformats/oas_server_gen.go
@@ -0,0 +1,34 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"context"
+)
+
+// Handler handles operations described by OpenAPI v3 specification.
+type Handler interface {
+	// PhoneGet implements GET /phone operation.
+	//
+	// GET /phone
+	PhoneGet(ctx context.Context, req *User, params PhoneGetParams) (*User, error)
+}
+
+// Server implements http server based on OpenAPI v3 specification and
+// calls Handler to handle requests.
+type Server struct {
+	h Handler
+	baseServer
+}
+
+// NewServer creates new Server.
+func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
+	s, err := newServerConfig(opts...).baseServer()
+	if err != nil {
+		return nil, err
+	}
+	return &Server{
+		h:          h,
+		baseServer: s,
+	}, nil
+}
diff --git a/internal/integration/test_customformats/oas_unimplemented_gen.go b/internal/integration/test_customformats/oas_unimplemented_gen.go
new file mode 100644
index 00000000..f447223b
--- /dev/null
+++ b/internal/integration/test_customformats/oas_unimplemented_gen.go
@@ -0,0 +1,21 @@
+// Code generated by ogen, DO NOT EDIT.
+
+package api
+
+import (
+	"context"
+
+	ht "github.com/ogen-go/ogen/http"
+)
+
+// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
+type UnimplementedHandler struct{}
+
+var _ Handler = UnimplementedHandler{}
+
+// PhoneGet implements GET /phone operation.
+//
+// GET /phone
+func (UnimplementedHandler) PhoneGet(ctx context.Context, req *User, params PhoneGetParams) (r *User, _ error) {
+	return r, ht.ErrNotImplemented
+}