/
validate.spec.js
88 lines (75 loc) · 2.46 KB
/
validate.spec.js
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
import { validate } from '@/validate';
import { extend } from '@/extend';
import { confirmed, numeric } from '@/rules';
test('returns custom error messages passed in ValidationOptions', async () => {
extend('truthy', {
validate: Boolean,
message: 'Original Message'
});
const customMessage = 'Custom Message';
const value = false;
const rules = 'truthy';
const options = {
customMessages: {
truthy: customMessage
}
};
const result = await validate(value, rules, options);
expect(result.errors[0]).toEqual(customMessage);
});
describe('target field placeholder', () => {
extend('confirmed', {
...confirmed,
message: '{_field_} must match {_target_}'
});
const names = { foo: 'Foo', bar: 'Bar', baz: 'Baz' };
test('uses target field name, if supplied in options', async () => {
const values = { foo: 10, bar: 20 };
const rules = 'confirmed:foo';
const options = {
name: names.bar,
values,
names
};
const result = await validate(values.bar, rules, options);
expect(result.errors[0]).toEqual('Bar must match Foo');
});
test('uses target field key, if target field name not supplied in options', async () => {
const values = { foo: 10, bar: 20 };
const rules = 'confirmed:foo';
const options = {
name: names.bar,
values
};
const result = await validate(values.bar, rules, options);
expect(result.errors[0]).toEqual('Bar must match foo');
});
test('works for multiple targets', async () => {
extend('sum_of', {
message: '{_field_} must be the sum of {_aTarget_} and {_bTarget_}',
// eslint-disable-next-line prettier/prettier
params: [
{ name: 'a', isTarget: true },
{ name: 'b', isTarget: true }
],
validate: (value, { a, b }) => value === parseInt(a, 10) + parseInt(b, 10)
});
const values = { foo: 10, bar: 10, baz: 10 };
const names = { foo: 'Foo', bar: 'Bar', baz: 'Baz' };
const rules = 'sum_of:bar,baz';
const options = {
name: names.foo,
values,
names
};
const result = await validate(values.foo, rules, options);
expect(result.errors[0]).toEqual('Foo must be the sum of Bar and Baz');
});
});
test('allows empty rules for the string format', async () => {
extend('numeric', numeric);
let result = await validate(100, '|numeric');
expect(result.valid).toBe(true);
result = await validate(100, '||||numeric');
expect(result.valid).toBe(true);
});