valico 4.0.0

JSON Schema validator and JSON coercer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
## What is Valico?

[![Build Status](https://travis-ci.org/rustless/valico.svg?branch=master)](https://travis-ci.org/rustless/valico)

Valico is a validation and coercion tool for JSON objects, written in Rust. It designed to be a support library for the various REST-like frameworks or other tools that need to validate and coerce JSON input from outside world.

Valico has two features:

* **DSL** — a set of simple validators and coercers inspired by [Grape]. It has built-in support for common coercers, validators and can return detailed error messages if something goes wrong.
* **JSON Schema** — An implementation of JSON Schema, based on IETF's draft v7.

References:

* http://json-schema.org
* http://json-schema.org/latest/json-schema-core.html
* http://json-schema.org/latest/json-schema-validation.html

```toml
# Cargo.toml
valico = "2"
```

[API docs](http://rustless.org/valico/doc/valico/)

## JSON Schema

It passes the entire [JSON-Schema-Test-Suite](https://github.com/json-schema/JSON-Schema-Test-Suite/tree/develop/tests/draft4) except for remoteRefs and maxLength/minLength when using unicode surrogate pairs. It also can validate your schema and give you an explanation about what is wrong in it.

### Example

~~~rust
extern crate serde_json;
extern crate valico;

use serde_json::Value;
use valico::json_schema;
use std::fs::File;

fn main() {
    let json_schema: Value = serde_json::from_reader(File::open("tests/schema/schema.json").unwrap()).unwrap();

    let mut scope = json_schema::Scope::new();
    let schema = scope.compile_and_return(json_v4_schema.clone(), false).unwrap();

    println!("Is valid: {}", schema.validate(&json_v4_schema).is_valid());
}
~~~

### JSON Schema builder

Valico goes with `valico::json_schema::schema(|scheme| { /* .. */ }) -> json::Json` function that allows to use simple DSL to generate your schemes. It allows you not to use strings and raw JSON manipulation. It also prevent some kinds of spelling and type errors.

~~~rust
builder::schema(|s| {
    s.properties(|properties| {
        properties.insert("prop1", |prop1| {
            prop1.maximum(10f64, false);
        });
    });
    s.pattern_properties(|properties| {
        properties.insert("prop.*", |prop| {
            prop.maximum(1000f64, false);
        });
    });
    s.additional_properties_schema(|additional| {
        additional.maximum(5f64, false)
    });
})
~~~

TODO more docs about JSON Schema here

## DSL

### Basic Usage

All Valico stuff is making by Builder instance. Below is a simple example showing how one can create and setup Builder:

~~~rust
let params = Builder::build(|params| {
	params.req_nested("user", Builder::list(), |params| {
		params.req_typed("name", json_dsl::string());
		params.req_typed("friend_ids", json_dsl::array_of(json_dsl::u64()))
	});
});
~~~

Later `params` instance can be used to process one or more JSON objects with it's `process` method with signature `fn process(&self, tree: &mut JsonObject) -> ValicoResult<()>`.

**Note** that Valico will **mutate** borrowed JSON value if some coercion is needed.

Example:

~~~rust
extern crate valico;
extern crate serde_json;

use valico::json_dsl;
use serde_json::{from_str, to_string_pretty};

fn main() {

    let params = json_dsl::Builder::build(|params| {
        params.req_nested("user", json_dsl::array(), |params| {
            params.req_typed("name", json_dsl::string());
            params.req_typed("friend_ids", json_dsl::array_of(json_dsl::u64()))
        });
    });

    let mut obj = from_str(r#"{"user": {"name": "Frodo", "friend_ids": ["1223"]}}"#).unwrap();

    let state = params.process(&mut obj, &None);
    if state.is_valid() {
        println!("Result object is {}", to_string_pretty(&obj).unwrap());
    } else {
        panic!("Errors during process: {:?}", state);
    }

}
~~~

Also you can look to the [specs] for more details and examples.

[specs]: https://github.com/s-panferov/valico/blob/master/tests/builder.rs

### Validation and coercion

You can define validations and coercion options for your parameters using a `Builder::build` block. Parameters can be **optional** and **required**. Requires parameters must be always present. Optional parameters can be omitted.

When parameter is present in JSON all validation and coercions will be applied and error fired if something goes wrong.

#### Builder

This functions are available in Builder to define parameters:

~~~rust

// Parameter is required, no coercion
fn req_defined(&mut self, name: &str);

// Parameter is required, with coercion
fn req_typed(&mut self, name: &str, coercer: Box<Coercer>);

// Parameter is required, with coercion and nested checks
fn req_nested(&mut self, name: &str, coercer: Box<Coercer>, nest_def: |&mut Builder|);

// Parameter is required, setup with Param DSL
fn req(&mut self, name: &str, param_builder: |&mut Param|);

// Parameter is optional, no coercion
fn opt_defined(&mut self, name: &str);

// Parameter is optional, with coercion
fn opt_typed(&mut self, name: &str, coercer: Box<Coercer>);

// Parameter is optional, with coercion and nested checks
fn opt_nested(&mut self, name: &str, coercer: Box<Coercer>, nest_def: |&mut Builder|);

// Parameter is required, setup with Param DSL
fn opt(&mut self, name: &str, param_builder: |&mut Param|);

~~~

#### Built-in Coercers

Available list of coercers:

* json_dsl::i64()
* json_dsl::u64()
* json_dsl::f64()
* json_dsl::string()
* json_dsl::boolean()
* json_dsl::null()
* json_dsl::array()
* json_dsl::array_of()
* json_dsl::encoded_array() — use it for string-encoded arrays e.g. "red,green,blue" -> ["red", "green", "blue"]
* json_dsl::encoded_array_of() — use it for string-encoded arrays of some type e.g. "1,2,3" -> [1, 2, 3]
* json_dsl::object()

Example of usage:

~~~rust
let params = Builder::build(|params| {
    params.req_typed("id", json_dsl::u64());
    params.req_typed("name", json_dsl::string());
    params.opt_typed("is_active", json_dsl::boolean());
    params.opt_typed("tags", json_dsl::array_of(json_dsl::strings()));
});
~~~

#### Nested processing

You can specify rules to nesting processing for **lists** and **objects**:

~~~rust
let params = Builder::build(|params| {
    params.req_nested("user", json_dsl::object(), |params| {
        params.req_typed("name", json_dsl::string());
        params.opt_typed("is_active", json_dsl::boolean());
        params.opt_typed("tags", json_dsl::array_of(json_dsl::strings()));
    });
});

let params = Builder::build(|params| {
    params.req_nested("users", Builder::list(), |params| {
        params.req_typed("name", json_dsl::string());
        params.opt_typed("is_active", json_dsl::boolean());
        params.opt_typed("tags", json_dsl::array_of(json_dsl::strings()));
    });
});
~~~

Nesting level is not limited in Valico.

#### Validate with JSON Schema

DSL allows to use JSON Schema validations to validate objects at the Builder level and the Param level:

~~~rust
let params = json_dsl::Builder::build(|params| {
    params.req("a", |a| {
        a.schema(|schema| {
            schema.integer();
            schema.maximum(10f64, false);
        })
    });
});
~~~

Note that JSON Schema validates object AFTER coerce pass:

~~~rust
let mut params = json_dsl::Builder::build(|params| {
    params.req("a", |a| {
        a.coerce(json_dsl::u64());
        a.schema(|schema| {
            schema.maximum(10f64, false);
        })
    });
});
~~~

Don't forget to create a `json_schema::Scope` BEFORE processing:

~~~rust
let mut scope = json_schema::Scope::new();
params.build_schemes(&mut scope).unwrap();
~~~

#### Parameters DSL

You can use DSL block to setup parameters with more flexible way:

~~~rust
let params = Builder::build(|params| {
    params.req("user", |user| {
        user.desc("Parameter is used to create new user");
        user.coerce(json_dsl::object());

        // this allows null to be a valid value
        user.allow_null();

        user.nest(|params| {
            params.req_typed("name", json_dsl::string());
            params.opt("kind", |kind| {
                kind.coerce(json_dsl::string());

                // optional parameters can have default values
                kind.default("simeple_user".to_string())
            });
        });
    });
});
~~~

#### Parameter validations

DSL supports several parameter validations. They considered outdated and likely to be **removed** in the future in favour of JSON Schema validation.

##### allow_values

Parameters can be restricted to a specific set of values with **allow_values**:

~~~rust
let params = Builder::build(|params| {
    params.req("kind", |kind| {
        kind.coerce(json_dsl::string());
        kind.allow_values(&["circle".to_string(), "square".to_string()]);
    })
})
~~~

##### reject_values

Some values can be rejected with **reject_values**:

~~~rust
let params = Builder::build(|params| {
    params.req("user_role", |kind| {
        kind.coerce(json_dsl::string());
        kind.reject_values(&["admin".to_string(), "manager".to_string()]);
    })
})
~~~

##### regex

String values can be tested with Regex:

~~~rust
let params = Builder::build(|params| {
    params.req("nickname", |a| {
        a.coerce(json_dsl::string());

        // force all nicknames to start with "Amazing"
        a.regex(regex!("^Amazing"));
    })
});
~~~

##### validate_with

Sometimes it's usefull to use some custom function as validator:

~~~rust
let params = Builder::build(|params| {
    params.req("pushkin_birthday", |a| {
        a.coerce(json_dsl::u64());

        fn guess(val: &Json) -> Result<(), String> {
            if *val == 1799u.to_json() {
                Ok(())
            } else {
                Err("No!".to_string())
            }
        }

        a.validate_with(guess);
    });
});
~~~

##### validate

One can use custom validator. Docs in Progress.

#### Builder validations

Some validators can be specified in Builder DSL block to validate a set of parameters.

##### mutually_exclusive

Parameters can be defined as mutually_exclusive, ensuring that they aren't present at the same time in a request.

~~~rust
let params = Builder::build(|params| {
    params.opt_defined("vodka");
    params.opt_defined("beer");

    params.mutually_exclusive(&["vodka", "beer"]);
});
~~~

Multiple sets can be defined:

~~~rust
let params = Builder::build(|params| {
    params.opt_defined("vodka");
    params.opt_defined("beer");
    params.mutually_exclusive(&["vodka", "beer"]);

    params.opt_defined("lard");
    params.opt_defined("jamon");
    params.mutually_exclusive(&["lard", "jamon"]);
});
~~~

**Warning**: Never define mutually exclusive sets with any required params. Two mutually exclusive required params will mean params are never valid. One required param mutually exclusive with an optional param will mean the latter is never valid.

##### exactly_one_of

Parameters can be defined as 'exactly_one_of', ensuring that exactly one parameter gets selected.

~~~rust
let params = Builder::build(|params| {
    params.opt_defined("vodka");
    params.opt_defined("beer");
    params.exactly_one_of(["vodka", "beer"]);
});
~~~

##### at_least_one_of

Parameters can be defined as 'at_least_one_of', ensuring that at least one parameter gets selected.

~~~rust
let params = Builder::build(|params| {
    params.opt_defined("vodka");
    params.opt_defined("beer");
    params.opt_defined("wine");
    params.exactly_one_of(["vodka", "beer", "wine"]);
});
~~~

##### validate_with

Sometimes it's usefull to use some custom function as validator:

~~~rust
let params = Builder::build(|params| {
    params.req_defined("monster_name");

    fn validate_params(_: &JsonObject) -> Result<(),String> {
        Err("YOU SHALL NOT PASS".to_string())
    }

    params.validate_with(validate_params);
});
~~~

##### validate

One can use custom validator. Docs in Progress.

## Building for other targets

### Web Assembly

For WebAssembly, enable the `js` feature:

```toml
# Cargo.toml
valico = { version = "2", features = ["js"] }
```