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 | 1×
1×
1×
1×
3×
1×
2×
1×
2×
1×
2×
1×
1×
12×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
| import assert from 'assert'
import Validators, { addValidator } from '../index'
import getErrorId from './helper'
const fooValidator = addValidator({
defaultMessage: 'form.errors.foo',
validator: function(options, value) {
return value === 'foo'
}
})
const barValidator = addValidator({
validator: function(options, value, allValues) {
return value === 'bar' && allValues['foobar'] === 'foobar'
}
})
const invalidValidator = addValidator({
validator: function(options, value) {
return options.invalid === 'valid'
}
})
const digitValidator = addValidator({
validator: function(options, value, allValues) {
if (options.digits !== value.replace(/[^0-9]/g, '').length) {
return { id: 'form.errors.digits' }
}
}
})
function test (validator, value, params, allValues) {
return getErrorId(validator(params)(value, allValues))
}
describe('Validator: addValidator', function() {
it('should be invalid', function() {
assert.equal('form.errors.foo', test(fooValidator, 'bar'))
assert.equal('form.errors.bar', test(barValidator, 'foo', { msg: 'form.errors.bar' }, { bar: 'foo' }))
assert.equal('form.errors.invalid', test(invalidValidator, '', { invalid: 'invalid' }))
assert.equal('form.errors.digits', test(digitValidator, '1 23', { digits: 4 }))
})
it('should be valid', function() {
assert.ok(!test(fooValidator, 'foo'))
assert.ok(!test(fooValidator, '', { allowBlank: true }))
assert.ok(!test(fooValidator, 'bar', { if: function() { return false } }))
assert.ok(!test(fooValidator, 'bar', { unless: function() { return true } }))
assert.ok(!test(barValidator, 'bar', {}, { foobar: 'foobar' }))
assert.ok(!test(invalidValidator, '', { invalid: 'valid' }))
assert.ok(!test(digitValidator, '1 2 3 4', { digits: 4 }))
})
it('should use formatMessage', function() {
let defaultValue = Validators.formatMessage
Validators.formatMessage = function(msg) {
return Object.assign({}, msg, { id: msg.id + '2' })
}
assert.equal('form.errors.foo2', test(fooValidator, 'bar'))
Validators.formatMessage = defaultValue;
})
})
|