-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
yii.validation.test.js
1693 lines (1532 loc) · 76 KB
/
yii.validation.test.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var assert = require('chai').assert;
assert.isDeferred = function (object) {
if (typeof object.resolve !== 'function') {
return false;
}
return String(object.resolve) === String($.Deferred().resolve);
};
var sinon;
var withData = require('leche').withData;
var StringUtils = {
repeatString: function (value, times) {
return (new Array(times + 1)).join(value);
}
};
var jsdom = require('mocha-jsdom');
var punycode = require('../../../vendor/bower-asset/punycode/punycode');
var fs = require('fs');
var vm = require('vm');
var yii;
describe('yii.validation', function () {
var VALIDATOR_SUCCESS_MESSAGE = 'should leave messages as is';
var VALIDATOR_ERROR_MESSAGE = 'should add appropriate errors(s) to messages';
function getValidatorMessage(expectedResult) {
var isTrueBoolean = typeof expectedResult === 'boolean' && expectedResult === true;
var isEmptyArray = Array.isArray(expectedResult) && expectedResult.length === 0;
return isTrueBoolean || isEmptyArray ? VALIDATOR_SUCCESS_MESSAGE : VALIDATOR_ERROR_MESSAGE;
}
var $;
var code;
var script;
function FileReader() {
this.readAsDataURL = function() {
};
}
function Image() {
}
function registerTestableCode(customSandbox) {
if (customSandbox === undefined) {
customSandbox = {
File: {},
FileReader: FileReader,
Image: Image,
punycode: punycode
};
}
var path = 'framework/assets/yii.validation.js';
if (code === undefined) {
code = fs.readFileSync(path);
}
if (script === undefined) {
script = new vm.Script(code);
}
var defaultSandbox = {yii: {}, jQuery: $};
var sandbox = $.extend({}, defaultSandbox, customSandbox);
var context = new vm.createContext(sandbox);
script.runInContext(context);
yii = sandbox.yii;
}
jsdom({
src: fs.readFileSync('vendor/bower-asset/jquery/dist/jquery.js', 'utf-8')
});
before(function () {
$ = window.$;
registerTestableCode();
sinon = require('sinon');
});
it('should exist', function () {
assert.isObject(yii.validation);
});
describe('isEmpty method', function () {
withData({
'undefined': [undefined, true],
'null': [null, true],
'empty array': [[], true],
'empty string': ['', true],
'string containing whitespace': [' ', false],
'empty object': [{}, false],
'non-zero integer': [1, false],
'non-empty string': ['a', false],
'non-empty array': [[1], false]
}, function (value, expectedValue) {
var message = expectedValue ? 'should return "true"' : 'should return "false"';
it(message, function () {
assert.strictEqual(yii.validation.isEmpty(value), expectedValue);
});
});
});
describe('addMessage method', function () {
withData({
'empty messages': [[], 'Message', 1, ['Message']],
'non-empty messages': [['Message 1'], 'Message 2', 1, ['Message 1', 'Message 2']],
'message as template': [[], 'Message with value {value}', 1, ['Message with value 1']]
}, function (messages, message, value, expectedMessages) {
it('should extend messages and replace value in template', function () {
yii.validation.addMessage(messages, message, value);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('required validator', function () {
withData({
'empty string': ['', {}, false],
'empty string, strict mode': ['', {strict: true}, true],
'string containing whitespace': [' ', {}, false],
'string containing whitespace, strict mode': [' ', {strict: true}, true],
'non-empty string': ['a', {}, true],
'undefined': [undefined, {}, false],
'undefined, strict mode': [undefined, {strict: true}, false],
// requiredValue
'integer and required value set to different integer': [1, {requiredValue: 2}, false],
'string and required value set to integer with the same value': ['1', {requiredValue: 1}, true],
'string and required value set to integer with the same value, strict mode': [
'1',
{requiredValue: 1, strict: true},
false
],
'integer and required value set to same integer, strict mode': [
1,
{requiredValue: 1, strict: true},
true
]
}, function (value, options, expectValid) {
it(getValidatorMessage(expectValid), function () {
options.message = 'This field is required.';
var messages = [];
var expectedMessages = expectValid ? [] : ['This field is required.'];
yii.validation.required(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('boolean validator', function () {
var defaultOptions = {
message: 'The value must have a boolean type.',
trueValue: '1',
falseValue: '0'
};
withData({
'empty string': ['', {}, false],
'empty string, skip on empty': ['', {skipOnEmpty: true}, true],
'non-empty string, does not equal neither trueValue no falseValue': ['a', {}, false],
'integer, value equals falseValue': [0, {}, true],
'integer, value equals trueValue': [1, {}, true],
'string equals falseValue': ['0', {}, true],
'string equals trueValue': ['1', {}, true],
'integer, value equals falseValue, strict mode': [0, {strict: true}, false],
'integer, value equals trueValue, strict mode': [1, {strict: true}, false],
// trueValue, falseValue
'string equals custom trueValue, custom trueValue is set': ['yes', {trueValue: 'yes'}, true],
'string does not equal neither trueValue no falseValue, custom trueValue is set': [
'no',
{trueValue: 'yes'},
false
],
'string equals custom falseValue, custom falseValue is set': ['no', {falseValue: 'no'}, true],
'string does not equal neither trueValue no falseValue, custom falseValue is set': [
'yes',
{falseValue: 'no'},
false
],
'string equals custom trueValue, custom trueValue and falseValue are set': [
'yes',
{trueValue: 'yes', falseValue: 'no'},
true
],
'string equals custom falseValue, custom trueValue and falseValue are set': [
'no',
{trueValue: 'yes', falseValue: 'no'},
true
],
'string does not equal neither custom trueValue no falseValue, custom trueValue and falseValue are set': [
'a',
{trueValue: 'yes', falseValue: 'no'},
false
]
}, function (value, customOptions, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
var expectedMessages = expectValid ? [] : ['The value must have a boolean type.'];
yii.validation.boolean(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('string validator', function () {
var defaultOptions = {
message: 'Invalid type.',
tooShort: 'Too short.',
tooLong: 'Too long.',
notEqual: 'Not equal.'
};
withData({
'empty string': ['', {}, []],
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'non-empty string': ['a', {}, []],
'integer': [1, {}, ['Invalid type.']],
// min
'string less than min': ['Word', {min: 5}, ['Too short.']],
'string more than min': ['Some string', {min: 5}, []],
'string equals min': ['Equal', {min: 5}, []],
// max
'string less than max': ['Word', {max: 5}, []],
'string more than max': ['Some string', {max: 5}, ['Too long.']],
'string equals max': ['Equal', {max: 5}, []],
// is
'string equals exact length': ['Equal', {is: 5}, []],
'string does not equal exact length': ['Does not equal', {is: 5}, ['Not equal.']],
'string does not equal exact length and less than min': ['Word', {is: 5, min: 5}, ['Not equal.']],
// min and max
'string less than min, both min and max are set': ['Word', {min: 5, max: 10}, ['Too short.']],
'string in between of min and max, both min and max are set': ['Between', {min: 5, max: 10}, []],
'string more than max, both min and max are set': ['Some string', {min: 5, max: 10}, ['Too long.']]
}, function (value, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.string(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('file validator', function () {
var defaultOptions = {
message: 'Unable to upload a file.',
uploadRequired: 'Upload is required.',
tooMany: 'Too many files.',
wrongExtension: 'File {file} has wrong extension.',
wrongMimeType: 'File {file} has wrong mime type.',
tooSmall: 'File {file} is too small.',
tooBig: 'File {file} is too big.'
};
var attribute = {
input: '#input-id',
$form: 'jQuery form object'
};
var files;
var filesService = {
getFiles: function () {
return files;
}
};
var $input = {
get: function (value) {
return value === 0 ? {files: filesService.getFiles()} : undefined;
}
};
var jQueryInitStub;
var inputGetSpy;
var filesServiceSpy;
beforeEach(function () {
jQueryInitStub = sinon.stub($.fn, 'init');
jQueryInitStub.withArgs(attribute.input, attribute.$form).returns($input);
inputGetSpy = sinon.spy($input, 'get');
filesServiceSpy = sinon.spy(filesService, 'getFiles');
});
afterEach(function () {
jQueryInitStub.restore();
inputGetSpy.restore();
filesServiceSpy.restore();
});
describe('with File API is not available', function () {
beforeEach(function () {
registerTestableCode({File: undefined});
});
afterEach(function () {
registerTestableCode();
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
yii.validation.file(attribute, messages, defaultOptions);
assert.deepEqual(messages, []);
assert.isFalse(jQueryInitStub.called);
assert.isFalse(inputGetSpy.called);
assert.isFalse(filesServiceSpy.called);
});
});
describe('with File API is available', function () {
withData({
'files are not available': [undefined, {}, ['Unable to upload a file.']],
'no files': [[], {}, ['Upload is required.']],
'no files, skip on empty': [[], {skipOnEmpty: true}, []],
// maxFiles
'number of files less than maximum': [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{maxFiles: 2},
[]
],
'number of files equals maximum': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxFiles: 2},
[]
],
'number of files more than maximum': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 200 * 1024}
],
{maxFiles: 2},
['Too many files.']
],
// extensions
'files in extensions list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{extensions: ['jpg', 'png']},
[]
],
'file not in extensions list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{extensions: ['jpg', 'png']},
['File file.bmp has wrong extension.']
],
// mimeTypes
'mime type in mime types list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{mimeTypes: ['image/jpeg', 'image/png']},
[]
],
'mime type not in mime types list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{mimeTypes: ['image/jpeg', 'image/png']},
['File file.bmp has wrong mime type.']
],
// maxSize
'size less than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxSize: 200 * 1024},
[]
],
'size equals maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 100 * 1024}
],
{maxSize: 100 * 1024},
[]
],
'size more than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxSize: 50 * 1024},
['File file.jpg is too big.', 'File file.png is too big.']
],
// minSize
'size less than minimum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{minSize: 120 * 1024},
['File file.jpg is too small.']
],
'size equals minimum size': [
[
{name: 'file.jpg', type: 'image/bmp', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 100 * 1024}
],
{maxSize: 100 * 1024},
[]
],
'size more than minimum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{minSize: 80 * 1024},
[]
],
'one file is less than minimum size, one file is more than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 250 * 1024}
],
{minSize: 150 * 1024, maxSize: 200 * 1024},
['File file.jpg is too small.', 'File file.png is too big.']
]
}, function (uploadedFiles, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
files = uploadedFiles;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.file(attribute, messages, options);
assert.deepEqual(messages, expectedMessages);
assert.isTrue(jQueryInitStub.calledOnce);
assert.deepEqual(jQueryInitStub.getCall(0).args, [attribute.input, attribute.$form]);
assert.isTrue(inputGetSpy.calledOnce);
assert.deepEqual(inputGetSpy.getCall(0).args, [0]);
assert.isTrue(filesServiceSpy.calledOnce);
});
});
});
});
describe('image validator', function () {
var attribute = {
input: '#input-id',
$form: 'jQuery form object'
};
var files;
var filesService = {
getFiles: function () {
return files;
}
};
var $input = {
get: function (value) {
return value === 0 ? {files: filesService.getFiles()} : undefined;
}
};
var deferred;
var jQueryInitStub;
var inputGetSpy;
var filesServiceSpy;
var validateImageStub;
var deferredStub;
beforeEach(function () {
jQueryInitStub = sinon.stub($.fn, 'init');
jQueryInitStub.withArgs(attribute.input, attribute.$form).returns($input);
inputGetSpy = sinon.spy($input, 'get');
filesServiceSpy = sinon.spy(filesService, 'getFiles');
validateImageStub = sinon.stub(yii.validation, 'validateImage');
deferred = $.Deferred();
deferredStub = sinon.stub(deferred, 'resolve');
});
afterEach(function () {
jQueryInitStub.restore();
inputGetSpy.restore();
filesServiceSpy.restore();
validateImageStub.restore();
deferredStub.restore();
});
describe('with FileReader API is not available', function () {
beforeEach(function () {
registerTestableCode({FileReader: undefined});
});
afterEach(function () {
registerTestableCode();
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
files = [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024, width: 100, height: 100},
{name: 'file.png', type: 'image/png', size: 150 * 1024, width: 250, height: 250}
];
var messages = [];
var deferredList = [];
yii.validation.image(attribute, messages, {}, deferredList);
assert.deepEqual(messages, []);
assert.isFalse(validateImageStub.called);
assert.isFalse(deferredStub.called);
assert.deepEqual(deferredList, []);
});
});
describe('with FileReader API is available', function () {
it(VALIDATOR_ERROR_MESSAGE, function () {
files = [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024, width: 100, height: 100},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024, width: 250, height: 250}
];
var options = {
extensions: ['jpg', 'png'],
wrongExtension: 'File {file} has wrong extension.',
minWidth: 200,
underWidth: 'File {file} has small width.'
};
var messages = [];
var deferredList = [];
yii.validation.image(attribute, messages, options, deferredList);
assert.deepEqual(messages, ['File file.bmp has wrong extension.']);
assert.equal(validateImageStub.callCount, files.length);
for (var i = 0; i < validateImageStub.callCount; i++) {
assert.equal(validateImageStub.getCall(i).args.length, 6);
assert.deepEqual(validateImageStub.getCall(i).args[0], files[i]);
assert.deepEqual(validateImageStub.getCall(i).args[1], ['File file.bmp has wrong extension.']);
assert.deepEqual(validateImageStub.getCall(i).args[2], options);
assert.isDeferred(validateImageStub.getCall(i).args[3]);
assert.instanceOf(validateImageStub.getCall(i).args[4], FileReader);
assert.instanceOf(validateImageStub.getCall(i).args[5], Image);
}
assert.equal(deferredList.length, files.length);
for (i = 0; i < deferredList.length; i++) {
assert.isDeferred(deferredList[i]);
}
});
});
});
describe('validateImage method', function () {
var file = {name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024};
var image = new Image();
var deferred;
var fileReader = new FileReader();
var deferredStub;
var fileReaderStub;
beforeEach(function () {
deferred = $.Deferred();
deferredStub = sinon.stub(deferred, 'resolve');
});
afterEach(function () {
deferredStub.restore();
fileReaderStub.restore();
});
function verifyStubs() {
assert.isTrue(fileReaderStub.calledOnce);
assert.isTrue(deferredStub.calledOnce);
}
describe('with error while reading data', function () {
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onerror();
});
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
yii.validation.validateImage(file, messages, {}, deferred, fileReader, image);
assert.deepEqual(messages, []);
verifyStubs();
});
});
describe('with error while reading image', function () {
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onload = function () {
image.onerror();
};
this.onload();
});
});
it(VALIDATOR_ERROR_MESSAGE, function () {
var messages = [];
var options = {notImage: 'File {file} is not an image.'};
yii.validation.validateImage(file, messages, options, deferred, fileReader, image);
assert.deepEqual(messages, ['File file.jpg is not an image.']);
verifyStubs();
});
});
describe('with successfully read image', function () {
var defaultOptions = {
underWidth: 'File {file} has small width.',
overWidth: 'File {file} has big width.',
underHeight: 'File {file} has small height.',
overHeight: 'File {file} has big height.'
};
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onload = function () {
image.onload();
};
this.onload();
});
});
withData({
// minWidth
'width less than minimum width': [
{width: 100, height: 100},
{minWidth: 200},
['File file.jpg has small width.']
],
'width equals minimum width': [{width: 100, height: 100}, {minWidth: 100}, []],
'width more than minimum width': [{width: 200, height: 200}, {minWidth: 100}, []],
// maxWidth
'width less than maximum width': [{width: 100, height: 100}, {maxWidth: 200}, []],
'width equals maximum width': [{width: 100, height: 100}, {maxWidth: 100}, []],
'width more than maximum width': [
{width: 200, height: 200},
{maxWidth: 100},
['File file.jpg has big width.']
],
// minHeight
'height less than minimum height': [
{width: 100, height: 100},
{minHeight: 200},
['File file.jpg has small height.']
],
'height equals minimum height': [{width: 100, height: 100}, {minHeight: 100}, []],
'height more than minimum height': [{width: 200, height: 200}, {minHeight: 100}, []],
// maxHeight
'height less than maximum height': [{width: 100, height: 100}, {maxHeight: 200}, []],
'height equals maximum height': [{width: 100, height: 100}, {maxHeight: 100}, []],
'height more than maximum height': [
{width: 200, height: 200},
{maxHeight: 100},
['File file.jpg has big height.']
],
// minWidth and minHeight
'width less than minimum width and height less than minimum height': [
{width: 100, height: 100},
{minWidth: 200, minHeight: 200},
['File file.jpg has small width.', 'File file.jpg has small height.']
]
}, function (imageSize, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
image.width = imageSize.width;
image.height = imageSize.height;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.validateImage(file, messages, options, deferred, fileReader, image);
assert.deepEqual(messages, expectedMessages);
verifyStubs();
});
});
});
});
describe('number validator', function () {
var integerPattern = /^\s*[+-]?\d+\s*$/;
var numberPattern = /^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/;
var defaultOptions = {
message: 'Not a number.',
tooSmall: 'Number is too small.',
tooBig: 'Number is too big.'
};
describe('with integer pattern', function () {
withData({
'empty string': ['', false],
'non-empty string': ['a', false],
'zero': ['0', true],
'positive integer, no sign': ['2', true],
'positive integer with sign': ['+2', true],
'negative integer': ['-2', true],
'decimal fraction with dot': ['2.5', false],
'decimal fraction with comma': ['2,5', false]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {pattern: integerPattern});
var messages = [];
var expectedMessages = expectValid ? [] : ['Not a number.'];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with number pattern', function () {
withData({
'empty string': ['', false],
'non-empty string': ['a', false],
'zero': ['0', true],
'positive integer, no sign': ['2', true],
'positive integer with sign': ['+2', true],
'negative integer': ['-2', true],
'decimal fraction with dot, no sign': ['2.5', true],
'positive decimal fraction with dot and sign': ['+2.5', true],
'negative decimal fraction with dot': ['-2.5', true],
'decimal fraction with comma': ['2,5', false],
'floating number with exponential part': ['-1.23e-10', true]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {pattern: numberPattern});
var messages = [];
var expectedMessages = expectValid ? [] : ['Not a number.'];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with different options, integer pattern', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
// Not a string
'undefined': [undefined, {}, []],
'integer, fits pattern': [2, {}, []],
'integer, does not fit pattern': [2.5, {}, []],
// min
'less than minimum': ['1', {min: 2}, ['Number is too small.']],
'equals minimum': ['2', {min: 2}, []],
'more than minimum': ['3', {min: 2}, []],
'wrong integer and less than min': ['1.5', {min: 2}, ['Not a number.']],
// max
'less than maximum': ['1', {max: 2}, []],
'equals maximum': ['2', {max: 2}, []],
'more than maximum': ['3', {max: 2}, ['Number is too big.']]
}, function (value, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
customOptions.pattern = integerPattern;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('range validator', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'array and arrays are not allowed': [['a', 'b'], {}, ['Invalid value.']],
'string in array': ['a', {range: ['a', 'b', 'c']}, []],
'string not in array': ['d', {range: ['a', 'b', 'c']}, ['Invalid value.']],
'array in array': [['a', 'b'], {range: ['a', 'b', 'c'], allowArray: true}, []],
'array not in array': [['a', 'd'], {range: ['a', 'b', 'c'], allowArray: true}, ['Invalid value.']],
'string in array and inverted logic': ['a', {range: ['a', 'b', 'c'], not: true}, ['Invalid value.']],
'string not in array and inverted logic': ['d', {range: ['a', 'b', 'c'], not: true}, []],
'array in array and inverted logic': [
['a', 'b'],
{range: ['a', 'b', 'c'], allowArray: true, not: true},
['Invalid value.']
],
'array not in array and inverted logic': [
['a', 'd'],
{range: ['a', 'b', 'c'], allowArray: true, not: true},
[]
]
}, function (value, options, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
options.message = 'Invalid value.';
var messages = [];
yii.validation.range(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('regular expression validator', function () {
var integerPattern = /^\s*[+-]?\d+\s*$/;
describe('with integer pattern', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'regular integer': ['2', {}, []],
'non-integer': ['2.5', {}, ['Invalid value.']],
'regular integer, inverted logic': ['2', {not: true}, ['Invalid value.']],
'integer pattern, non-integer, inverted logic': ['2.5', {pattern: integerPattern, not: true}, []]
}, function (value, options, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
options.message = 'Invalid value.';
options.pattern = integerPattern;
var messages = [];
yii.validation.regularExpression(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('email validator', function () {
var pattern = "^[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9]" +
"(?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
pattern = new RegExp(pattern);
var fullPattern = "^[^@]*<[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@" +
"(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$";
fullPattern = new RegExp(fullPattern);
var defaultOptions = {
pattern: pattern,
fullPattern: fullPattern,
message: 'Invalid value.'
};
describe('with empty string, skip on empty', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
var options = $.extend({}, defaultOptions, {skipOnEmpty: true});
yii.validation.email('', messages, options);
assert.deepEqual(messages, []);
});
});
describe('with basic configuration', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'double dot': ['ex..ample@example.com', false],
'unicode in domain': ['example@äüößìà.de', false],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', false],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', false],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', false],
'angle brackets, no name': ['<mail@cebe.cc>', false],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', false],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
false
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, defaultOptions);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with allowed name', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'unicode in domain': ['example@äüößìà.de', false],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', false],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', true],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', true],
'angle brackets, no name': ['<mail@cebe.cc>', true],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', true],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
true
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {allowName: true});
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with enabled IDN', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'unicode in domain': ['example@äüößìà.de', true],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', true],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', false],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', false],
'angle brackets, no name': ['<mail@cebe.cc>', false],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', false],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
false
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false