/
parsley.js
2083 lines (2067 loc) · 89.3 KB
/
parsley.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
/*!
* Parsleyjs
* Guillaume Potier - <guillaume@wisembly.com>
* Version 2.0.7 - built Sat Jan 24 2015 14:50:11
* MIT Licensed
*
*/
!(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module depending on jQuery.
define(['jquery'], factory);
} else {
// No AMD. Register plugin with global jQuery object.
factory(jQuery);
}
}(function ($) {
// small hack for requirejs if jquery is loaded through map and not path
// see http://requirejs.org/docs/jquery.html
if ('undefined' === typeof $ && 'undefined' !== typeof window.jQuery)
$ = window.jQuery;
var ParsleyUtils = {
// Parsley DOM-API
// returns object from dom attributes and values
// if attr is given, returns bool if attr present in DOM or not
attr: function ($element, namespace, checkAttr) {
var
attribute,
obj = {},
msie = this.msieversion(),
regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof $element || 'undefined' === typeof $element[0])
return {};
for (var i in $element[0].attributes) {
attribute = $element[0].attributes[i];
if ('undefined' !== typeof attribute && null !== attribute && (!msie || msie >= 8 || attribute.specified) && regex.test(attribute.name)) {
if ('undefined' !== typeof checkAttr && new RegExp(checkAttr + '$', 'i').test(attribute.name))
return true;
obj[this.camelize(attribute.name.replace(namespace, ''))] = this.deserializeValue(attribute.value);
}
}
return 'undefined' === typeof checkAttr ? obj : false;
},
setAttr: function ($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
// Recursive object / array getter
get: function (obj, path) {
var
i = 0,
paths = (path || '').split('.');
while (this.isObject(obj) || this.isArray(obj)) {
obj = obj[paths[i++]];
if (i === paths.length)
return obj;
}
return undefined;
},
hash: function (length) {
return String(Math.random()).substring(2, length ? length + 2 : 9);
},
/** Third party functions **/
// Underscore isArray
isArray: function (mixed) {
return Object.prototype.toString.call(mixed) === '[object Array]';
},
// Underscore isObject
isObject: function (mixed) {
return mixed === Object(mixed);
},
// Zepto deserialize function
deserializeValue: function (value) {
var num;
try {
return value ?
value == "true" ||
(value == "false" ? false :
value == "null" ? null :
!isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value)
: value;
} catch (e) { return value; }
},
// Zepto camelize function
camelize: function (str) {
return str.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function (str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase();
},
// http://support.microsoft.com/kb/167820
// http://stackoverflow.com/questions/19999388/jquery-check-if-user-is-using-ie
msieversion: function () {
var
ua = window.navigator.userAgent,
msie = ua.indexOf('MSIE ');
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
return 0;
}
};
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
var ParsleyDefaults = {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'fist'|'last'|'none'
focus: 'first',
// `$.Event()` that will trigger validation. eg: `keyup`, `change`...
trigger: false,
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function (ParsleyField) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function (ParsleyField) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
var ParsleyAbstract = function() {};
ParsleyAbstract.prototype = {
asyncSupport: false,
actualizeOptions: function () {
this.options = this.OptionsFactory.get(this);
return this;
},
// ParsleyValidator validate proxy function . Could be replaced by third party scripts
validateThroughValidator: function (value, constraints, priority) {
return window.ParsleyValidator.validate(value, constraints, priority);
},
// Subscribe an event and a handler for a specific field or a specific form
// If on a ParsleyForm instance, it will be attached to form instance and also
// To every field instance for this form
subscribe: function (name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
return this;
},
// Same as subscribe above. Unsubscribe an event for field, or form + its fields
unsubscribe: function (name) {
$.unsubscribeTo(this, name.toLowerCase());
return this;
},
// Reset UI
reset: function () {
// Field case: just emit a reset event for UI
if ('ParsleyForm' !== this.__class__)
return $.emit('parsley:field:reset', this);
// Form case: emit a reset event for each field
for (var i = 0; i < this.fields.length; i++)
$.emit('parsley:field:reset', this.fields[i]);
$.emit('parsley:form:reset', this);
},
// Destroy Parsley instance (+ UI)
destroy: function () {
// Field case: emit destroy event to clean UI and then destroy stored instance
if ('ParsleyForm' !== this.__class__) {
this.$element.removeData('Parsley');
this.$element.removeData('ParsleyFieldMultiple');
$.emit('parsley:field:destroy', this);
return;
}
// Form case: destroy all its fields and then destroy stored instance
for (var i = 0; i < this.fields.length; i++)
this.fields[i].destroy();
this.$element.removeData('Parsley');
$.emit('parsley:form:destroy', this);
}
};
/*!
* validator.js
* Guillaume Potier - <guillaume@wisembly.com>
* Version 1.0.0 - built Sun Aug 03 2014 17:42:31
* MIT Licensed
*
*/
var Validator = ( function ( ) {
var exports = {};
/**
* Validator
*/
var Validator = function ( options ) {
this.__class__ = 'Validator';
this.__version__ = '1.0.0';
this.options = options || {};
this.bindingKey = this.options.bindingKey || '_validatorjsConstraint';
};
Validator.prototype = {
constructor: Validator,
/*
* Validate string: validate( string, Assert, string ) || validate( string, [ Assert, Assert ], [ string, string ] )
* Validate object: validate( object, Constraint, string ) || validate( object, Constraint, [ string, string ] )
* Validate binded object: validate( object, string ) || validate( object, [ string, string ] )
*/
validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) {
if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString )
throw new Error( 'You must validate an object or a string' );
// string / array validation
if ( 'string' === typeof objectOrString || _isArray(objectOrString) )
return this._validateString( objectOrString, AssertsOrConstraintOrGroup, group );
// binded object validation
if ( this.isBinded( objectOrString ) )
return this._validateBindedObject( objectOrString, AssertsOrConstraintOrGroup );
// regular object validation
return this._validateObject( objectOrString, AssertsOrConstraintOrGroup, group );
},
bind: function ( object, constraint ) {
if ( 'object' !== typeof object )
throw new Error( 'Must bind a Constraint to an object' );
object[ this.bindingKey ] = new Constraint( constraint );
return this;
},
unbind: function ( object ) {
if ( 'undefined' === typeof object._validatorjsConstraint )
return this;
delete object[ this.bindingKey ];
return this;
},
isBinded: function ( object ) {
return 'undefined' !== typeof object[ this.bindingKey ];
},
getBinded: function ( object ) {
return this.isBinded( object ) ? object[ this.bindingKey ] : null;
},
_validateString: function ( string, assert, group ) {
var result, failures = [];
if ( !_isArray( assert ) )
assert = [ assert ];
for ( var i = 0; i < assert.length; i++ ) {
if ( ! ( assert[ i ] instanceof Assert) )
throw new Error( 'You must give an Assert or an Asserts array to validate a string' );
result = assert[ i ].check( string, group );
if ( result instanceof Violation )
failures.push( result );
}
return failures.length ? failures : true;
},
_validateObject: function ( object, constraint, group ) {
if ( 'object' !== typeof constraint )
throw new Error( 'You must give a constraint to validate an object' );
if ( constraint instanceof Constraint )
return constraint.check( object, group );
return new Constraint( constraint ).check( object, group );
},
_validateBindedObject: function ( object, group ) {
return object[ this.bindingKey ].check( object, group );
}
};
Validator.errorCode = {
must_be_a_string: 'must_be_a_string',
must_be_an_array: 'must_be_an_array',
must_be_a_number: 'must_be_a_number',
must_be_a_string_or_array: 'must_be_a_string_or_array'
};
/**
* Constraint
*/
var Constraint = function ( data, options ) {
this.__class__ = 'Constraint';
this.options = options || {};
this.nodes = {};
if ( data ) {
try {
this._bootstrap( data );
} catch ( err ) {
throw new Error( 'Should give a valid mapping object to Constraint', err, data );
}
}
};
Constraint.prototype = {
constructor: Constraint,
check: function ( object, group ) {
var result, failures = {};
// check all constraint nodes.
for ( var property in this.nodes ) {
var isRequired = false;
var constraint = this.get(property);
var constraints = _isArray( constraint ) ? constraint : [constraint];
for (var i = constraints.length - 1; i >= 0; i--) {
if ( 'Required' === constraints[i].__class__ ) {
isRequired = constraints[i].requiresValidation( group );
continue;
}
}
if ( ! this.has( property, object ) && ! this.options.strict && ! isRequired ) {
continue;
}
try {
if (! this.has( property, this.options.strict || isRequired ? object : undefined ) ) {
// we trigger here a HaveProperty Assert violation to have uniform Violation object in the end
new Assert().HaveProperty( property ).validate( object );
}
result = this._check( property, object[ property ], group );
// check returned an array of Violations or an object mapping Violations
if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) ) {
failures[ property ] = result;
}
} catch ( violation ) {
failures[ property ] = violation;
}
}
return _isEmptyObject(failures) ? true : failures;
},
add: function ( node, object ) {
if ( object instanceof Assert || ( _isArray( object ) && object[ 0 ] instanceof Assert ) ) {
this.nodes[ node ] = object;
return this;
}
if ( 'object' === typeof object && !_isArray( object ) ) {
this.nodes[ node ] = object instanceof Constraint ? object : new Constraint( object );
return this;
}
throw new Error( 'Should give an Assert, an Asserts array, a Constraint', object );
},
has: function ( node, nodes ) {
nodes = 'undefined' !== typeof nodes ? nodes : this.nodes;
return 'undefined' !== typeof nodes[ node ];
},
get: function ( node, placeholder ) {
return this.has( node ) ? this.nodes[ node ] : placeholder || null;
},
remove: function ( node ) {
var _nodes = [];
for ( var i in this.nodes )
if ( i !== node )
_nodes[ i ] = this.nodes[ i ];
this.nodes = _nodes;
return this;
},
_bootstrap: function ( data ) {
if ( data instanceof Constraint )
return this.nodes = data.nodes;
for ( var node in data )
this.add( node, data[ node ] );
},
_check: function ( node, value, group ) {
// Assert
if ( this.nodes[ node ] instanceof Assert )
return this._checkAsserts( value, [ this.nodes[ node ] ], group );
// Asserts
if ( _isArray( this.nodes[ node ] ) )
return this._checkAsserts( value, this.nodes[ node ], group );
// Constraint -> check api
if ( this.nodes[ node ] instanceof Constraint )
return this.nodes[ node ].check( value, group );
throw new Error( 'Invalid node', this.nodes[ node ] );
},
_checkAsserts: function ( value, asserts, group ) {
var result, failures = [];
for ( var i = 0; i < asserts.length; i++ ) {
result = asserts[ i ].check( value, group );
if ( 'undefined' !== typeof result && true !== result )
failures.push( result );
// Some asserts (Collection for example) could return an object
// if ( result && ! ( result instanceof Violation ) )
// return result;
//
// // Vast assert majority return Violation
// if ( result instanceof Violation )
// failures.push( result );
}
return failures;
}
};
/**
* Violation
*/
var Violation = function ( assert, value, violation ) {
this.__class__ = 'Violation';
if ( ! ( assert instanceof Assert ) )
throw new Error( 'Should give an assertion implementing the Assert interface' );
this.assert = assert;
this.value = value;
if ( 'undefined' !== typeof violation )
this.violation = violation;
};
Violation.prototype = {
show: function () {
var show = {
assert: this.assert.__class__,
value: this.value
};
if ( this.violation )
show.violation = this.violation;
return show;
},
__toString: function () {
if ( 'undefined' !== typeof this.violation )
this.violation = '", ' + this.getViolation().constraint + ' expected was ' + this.getViolation().expected;
return this.assert.__class__ + ' assert failed for "' + this.value + this.violation || '';
},
getViolation: function () {
var constraint, expected;
for ( constraint in this.violation )
expected = this.violation[ constraint ];
return { constraint: constraint, expected: expected };
}
};
/**
* Assert
*/
var Assert = function ( group ) {
this.__class__ = 'Assert';
this.__parentClass__ = this.__class__;
this.groups = [];
if ( 'undefined' !== typeof group )
this.addGroup( group );
};
Assert.prototype = {
construct: Assert,
requiresValidation: function ( group ) {
if ( group && !this.hasGroup( group ) )
return false;
if ( !group && this.hasGroups() )
return false;
return true;
},
check: function ( value, group ) {
if ( !this.requiresValidation( group ) )
return;
try {
return this.validate( value, group );
} catch ( violation ) {
return violation;
}
},
hasGroup: function ( group ) {
if ( _isArray( group ) )
return this.hasOneOf( group );
// All Asserts respond to "Any" group
if ( 'Any' === group )
return true;
// Asserts with no group also respond to "Default" group. Else return false
if ( !this.hasGroups() )
return 'Default' === group;
return -1 !== this.groups.indexOf( group );
},
hasOneOf: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
if ( this.hasGroup( groups[ i ] ) )
return true;
return false;
},
hasGroups: function () {
return this.groups.length > 0;
},
addGroup: function ( group ) {
if ( _isArray( group ) )
return this.addGroups( group );
if ( !this.hasGroup( group ) )
this.groups.push( group );
return this;
},
removeGroup: function ( group ) {
var _groups = [];
for ( var i = 0; i < this.groups.length; i++ )
if ( group !== this.groups[ i ] )
_groups.push( this.groups[ i ] );
this.groups = _groups;
return this;
},
addGroups: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
this.addGroup( groups[ i ] );
return this;
},
/**
* Asserts definitions
*/
HaveProperty: function ( node ) {
this.__class__ = 'HaveProperty';
this.node = node;
this.validate = function ( object ) {
if ( 'undefined' === typeof object[ this.node ] )
throw new Violation( this, object, { value: this.node } );
return true;
};
return this;
},
Blank: function () {
this.__class__ = 'Blank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' !== value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
Callback: function ( fn ) {
this.__class__ = 'Callback';
this.arguments = Array.prototype.slice.call( arguments );
if ( 1 === this.arguments.length )
this.arguments = [];
else
this.arguments.splice( 0, 1 );
if ( 'function' !== typeof fn )
throw new Error( 'Callback must be instanciated with a function' );
this.fn = fn;
this.validate = function ( value ) {
var result = this.fn.apply( this, [ value ].concat( this.arguments ) );
if ( true !== result )
throw new Violation( this, value, { result: result } );
return true;
};
return this;
},
Choice: function ( list ) {
this.__class__ = 'Choice';
if ( !_isArray( list ) && 'function' !== typeof list )
throw new Error( 'Choice must be instanciated with an array or a function' );
this.list = list;
this.validate = function ( value ) {
var list = 'function' === typeof this.list ? this.list() : this.list;
for ( var i = 0; i < list.length; i++ )
if ( value === list[ i ] )
return true;
throw new Violation( this, value, { choices: list } );
};
return this;
},
Collection: function ( assertOrConstraint ) {
this.__class__ = 'Collection';
this.constraint = 'undefined' !== typeof assertOrConstraint ? (assertOrConstraint instanceof Assert ? assertOrConstraint : new Constraint( assertOrConstraint )) : false;
this.validate = function ( collection, group ) {
var result, validator = new Validator(), count = 0, failures = {}, groups = this.groups.length ? this.groups : group;
if ( !_isArray( collection ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < collection.length; i++ ) {
result = this.constraint ?
validator.validate( collection[ i ], this.constraint, groups ) :
validator.validate( collection[ i ], groups );
if ( !_isEmptyObject( result ) )
failures[ count ] = result;
count++;
}
return !_isEmptyObject( failures ) ? failures : true;
};
return this;
},
Count: function ( count ) {
this.__class__ = 'Count';
this.count = count;
this.validate = function ( array ) {
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
var count = 'function' === typeof this.count ? this.count( array ) : this.count;
if ( isNaN( Number( count ) ) )
throw new Error( 'Count must be a valid interger', count );
if ( count !== array.length )
throw new Violation( this, array, { count: count } );
return true;
};
return this;
},
Email: function () {
this.__class__ = 'Email';
this.validate = function ( value ) {
var regExp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !regExp.test( value ) )
throw new Violation( this, value );
return true;
};
return this;
},
EqualTo: function ( reference ) {
this.__class__ = 'EqualTo';
if ( 'undefined' === typeof reference )
throw new Error( 'EqualTo must be instanciated with a value or a function' );
this.reference = reference;
this.validate = function ( value ) {
var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
if ( reference !== value )
throw new Violation( this, value, { value: reference } );
return true;
};
return this;
},
GreaterThan: function ( threshold ) {
this.__class__ = 'GreaterThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold >= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
GreaterThanOrEqual: function ( threshold ) {
this.__class__ = 'GreaterThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold > value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
InstanceOf: function ( classRef ) {
this.__class__ = 'InstanceOf';
if ( 'undefined' === typeof classRef )
throw new Error( 'InstanceOf must be instanciated with a value' );
this.classRef = classRef;
this.validate = function ( value ) {
if ( true !== (value instanceof this.classRef) )
throw new Violation( this, value, { classRef: this.classRef } );
return true;
};
return this;
},
Length: function ( boundaries ) {
this.__class__ = 'Length';
if ( !boundaries.min && !boundaries.max )
throw new Error( 'Lenth assert must be instanciated with a { min: x, max: y } object' );
this.min = boundaries.min;
this.max = boundaries.max;
this.validate = function ( value ) {
if ( 'string' !== typeof value && !_isArray( value ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string_or_array } );
if ( 'undefined' !== typeof this.min && this.min === this.max && value.length !== this.min )
throw new Violation( this, value, { min: this.min, max: this.max } );
if ( 'undefined' !== typeof this.max && value.length > this.max )
throw new Violation( this, value, { max: this.max } );
if ( 'undefined' !== typeof this.min && value.length < this.min )
throw new Violation( this, value, { min: this.min } );
return true;
};
return this;
},
LessThan: function ( threshold ) {
this.__class__ = 'LessThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold <= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
LessThanOrEqual: function ( threshold ) {
this.__class__ = 'LessThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold < value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
NotNull: function () {
this.__class__ = 'NotNull';
this.validate = function ( value ) {
if ( null === value || 'undefined' === typeof value )
throw new Violation( this, value );
return true;
};
return this;
},
NotBlank: function () {
this.__class__ = 'NotBlank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' === value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
Null: function () {
this.__class__ = 'Null';
this.validate = function ( value ) {
if ( null !== value )
throw new Violation( this, value );
return true;
};
return this;
},
Range: function ( min, max ) {
this.__class__ = 'Range';
if ( 'undefined' === typeof min || 'undefined' === typeof max )
throw new Error( 'Range assert expects min and max values' );
this.min = min;
this.max = max;
this.validate = function ( value ) {
try {
// validate strings and objects with their Length
if ( ( 'string' === typeof value && isNaN( Number( value ) ) ) || _isArray( value ) )
new Assert().Length( { min: this.min, max: this.max } ).validate( value );
// validate numbers with their value
else
new Assert().GreaterThanOrEqual( this.min ).validate( value ) && new Assert().LessThanOrEqual( this.max ).validate( value );
return true;
} catch ( violation ) {
throw new Violation( this, value, violation.violation );
}
return true;
};
return this;
},
Regexp: function ( regexp, flag ) {
this.__class__ = 'Regexp';
if ( 'undefined' === typeof regexp )
throw new Error( 'You must give a regexp' );
this.regexp = regexp;
this.flag = flag || '';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !new RegExp( this.regexp, this.flag ).test( value ) )
throw new Violation( this, value, { regexp: this.regexp, flag: this.flag } );
return true;
};
return this;
},
Required: function () {
this.__class__ = 'Required';
this.validate = function ( value ) {
if ( 'undefined' === typeof value )
throw new Violation( this, value );
try {
if ( 'string' === typeof value )
new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value );
else if ( true === _isArray( value ) )
new Assert().Length( { min: 1 } ).validate( value );
} catch ( violation ) {
throw new Violation( this, value );
}
return true;
};
return this;
},
// Unique() or Unique ( { key: foo } )
Unique: function ( object ) {
this.__class__ = 'Unique';
if ( 'object' === typeof object )
this.key = object.key;
this.validate = function ( array ) {
var value, store = [];
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < array.length; i++ ) {
value = 'object' === typeof array[ i ] ? array[ i ][ this.key ] : array[ i ];
if ( 'undefined' === typeof value )
continue;
if ( -1 !== store.indexOf( value ) )
throw new Violation( this, array, { value: value } );
store.push( value );
}
return true;
};
return this;
}
};
// expose to the world these awesome classes
exports.Assert = Assert;
exports.Validator = Validator;
exports.Violation = Violation;
exports.Constraint = Constraint;
/**
* Some useful object prototypes / functions here
*/
// IE8<= compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf)
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
// Test if object is empty, useful for Constraint violations check
var _isEmptyObject = function ( obj ) {
for ( var property in obj )
return false;
return true;
};
var _isArray = function ( obj ) {
return Object.prototype.toString.call( obj ) === '[object Array]';
};
// AMD export
if ( typeof define === 'function' && define.amd ) {
define( 'vendors/validator.js/dist/validator',[],function() {
return exports;
} );
// commonjs export
} else if ( typeof module !== 'undefined' && module.exports ) {
module.exports = exports;
// browser
} else {
window[ 'undefined' !== typeof validatorjs_ns ? validatorjs_ns : 'Validator' ] = exports;
}
return exports;
} )( );
// This is needed for Browserify usage that requires Validator.js through module.exports
Validator = 'undefined' !== typeof Validator ? Validator : ('undefined' !== typeof module ? module.exports : null);
var ParsleyValidator = function (validators, catalog) {
this.__class__ = 'ParsleyValidator';
this.Validator = Validator;
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
ParsleyValidator.prototype = {
init: function (validators, catalog) {
this.catalog = catalog;
for (var name in validators)
this.addValidator(name, validators[name].fn, validators[name].priority, validators[name].requirementsTransformer);
$.emit('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function (locale) {
if ('undefined' === typeof this.catalog[locale])
throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function (locale, messages, set) {
if ('object' === typeof messages)
this.catalog[locale] = messages;
if (true === set)
return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function (locale, name, message) {
if ('undefined' === typeof this.catalog[locale])
this.catalog[locale] = {};
this.catalog[locale][name.toLowerCase()] = message;
return this;
},
validate: function (value, constraints, priority) {
return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments);
},
// Add a new validator
addValidator: function (name, fn, priority, requirementsTransformer) {
this.validators[name.toLowerCase()] = function (requirements) {
return $.extend(new Validator.Assert().Callback(fn, requirements), {
priority: priority,
requirementsTransformer: requirementsTransformer
});
};
return this;
},
updateValidator: function (name, fn, priority, requirementsTransformer) {
return this.addValidator(name, fn, priority, requirementsTransformer);
},
removeValidator: function (name) {
delete this.validators[name];
return this;
},
getErrorMessage: function (constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name)
message = this.catalog[this.locale][constraint.name][constraint.requirements];
else
message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
return '' !== message ? message : this.catalog[this.locale].defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMessage: function (string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters)
string = this.formatMessage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : '';
},
// Here is the Parsley default validators list.
// This is basically Validatorjs validators, with different API for some of them
// and a Parsley priority set
validators: {
notblank: function () {
return $.extend(new Validator.Assert().NotBlank(), { priority: 2 });
},
required: function () {
return $.extend(new Validator.Assert().Required(), { priority: 512 });
},
type: function (type) {
var assert;
switch (type) {
case 'email':
assert = new Validator.Assert().Email();
break;
// range type just ensure we have a number here
case 'range':
case 'number':
assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$');
break;
case 'integer':
assert = new Validator.Assert().Regexp('^-?\\d+$');
break;
case 'digits':
assert = new Validator.Assert().Regexp('^\\d+$');
break;
case 'alphanum':
assert = new Validator.Assert().Regexp('^\\w+$', 'i');
break;
case 'url':
assert = new Validator.Assert().Regexp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-z]{2,24}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i');
break;
default:
throw new Error('validator type `' + type + '` is not supported');
}
return $.extend(assert, { priority: 256 });
},
pattern: function (regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
}
return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 });
},
minlength: function (value) {
return $.extend(new Validator.Assert().Length({ min: value }), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});