forked from guillaumepotier/Parsley.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsley.js
906 lines (774 loc) · 29.4 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
/*
* Parsley.js allows you to verify your form inputs frontend side, without writing a line of javascript. Or so..
*
* Author: Guillaume Potier - @guillaumepotier
*/
!function ($) {
"use strict";
/**
* Validator class stores all constraints functions and associated messages.
* Provides public interface to add, remove or modify them
*
* @class Validator
* @constructor
*/
var Validator = function ( options ) {
this.init( options );
}
Validator.prototype = {
constructor: Validator
/**
* Error messages
*
* @property messages
* @type {Object}
*/
, messages: {
defaultMessage: "This value seems to be invalid."
, type: {
email: "This value should be a valid email."
, url: "This value should be a valid url."
, number: "This value should be a valid number."
, digits: "This value should be digits."
, dateIso: "This value should be a valid date (YYYY-MM-DD)."
, alphanum: "This value should be alphanumeric."
}
, notnull: "This value should not be null."
, notblank: "This value should not be blank."
, required: "This value is required."
, regexp: "This value seems to be invalid."
, min: "This value should be greater than %s."
, max: "This value should be lower than %s."
, range: "This value should be between %s and %s."
, minlength: "This value is too short. It should have %s characters or more."
, maxlength: "This value is too long. It should have %s characters or less."
, rangelength: "This value length is invalid. It should be between %s and %s characters long."
, equalto: "This value should be the same."
}
/**
* Validator list. Built-in validators functions
*
* @property validators
* @type {Object}
*/
, validators: {
notnull: function ( val ) {
return val.length > 0;
}
, notblank: function ( val ) {
return '' !== val.replace( /^\s+/g, '' ).replace( /\s+$/g, '' );
}
// Works on all inputs. val is object for checkboxes
, required: function ( val ) {
// check here that at least a checkbox is checked here
if ( 'object' === typeof val ) {
return val.length > 0;
}
return this.notnull( val ) && this.notblank( val );
}
, type: function ( val, type ) {
var regExp;
switch ( type ) {
case "number":
regExp = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
break;
case "digits":
regExp = /^\d+$/;
break;
case "alphanum":
regExp = /^\w+$/;
break;
case "email":
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;
break;
case "url":
regExp = /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([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])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
break;
case "dateIso":
regExp = /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])$/;
break;
default:
return false;
break;
}
// test regExp if not null
return '' !== val ? regExp.test( val ) : false;
}
, regexp: function ( val, regExp ) {
return new RegExp( regExp, 'i' ).test( val );
}
, minlength: function ( val, min ) {
return val.length >= min;
}
, maxlength: function ( val, max ) {
return val.length <= max;
}
, rangelength: function ( val, arrayRange ) {
return this.minlength( val, arrayRange[ 0 ] ) && this.maxlength( val, arrayRange[ 1 ] );
}
, min: function ( val, min ) {
return val >= min;
}
, max: function ( val, max ) {
return val <= max;
}
, range: function ( val, arrayRange ) {
return val >= arrayRange[ 0 ] && val <= arrayRange[ 1 ];
}
, equalto: function ( val, elem ) {
return val === $( elem ).val();
}
, remote: function ( val, url, self ) {
var result = null
, data = {}
, dataType = {};
data[ self.$element.attr( 'name' ) ] = val;
if ( 'undefined' !== typeof self.options.remoteDatatype ) {
dataType = { dataType: self.options.remoteDatatype };
}
var manage = function ( isConstraintValid ) {
self.updateConstraint( "remote", "isValid", isConstraintValid );
self.manageValidationResult();
}
$.ajax( $.extend( {}, {
url: url
, data: data
, async: self.async
, method: self.options.remoteMethod || "GET"
, success: function ( response ) {
manage( "1" === response
|| "true" == response
|| ( 'object' === typeof response && 'undefined' !== typeof response.success )
|| new RegExp( "success", "i" ).test( response )
);
}
, error: function ( response ) {
manage( false );
}
}, dataType ) );
if ( self.async ) {
manage( result );
}
return result;
}
/**
* Aliases for checkboxes constraints
*/
, mincheck: function ( obj, val ) {
return this.minlength( obj, val );
}
, maxcheck: function ( obj, val ) {
return this.maxlength( obj, val);
}
, rangecheck: function ( obj, arrayRange ) {
return this.rangelength( obj, arrayRange );
}
}
/*
* Register custom validators and messages
*/
, init: function ( options ) {
var customValidators = options.validators
, customMessages = options.messages;
for ( var i in customValidators ) {
this.addValidator(i, customValidators[ i ]);
}
for ( var i in customMessages ) {
this.addMessage(i, customMessages[ i ]);
}
}
/**
* Replace %s placeholders by values
*
* @method formatMesssage
* @param {String} message Message key
* @param {Mixed} args Args passed by validators functions. Could be string, number or object
* @return {String} Formatted string
*/
, formatMesssage: function ( message, args ) {
if ( 'object' === typeof args ) {
for ( var i in args ) {
message = this.formatMesssage( message, args[ i ] );
}
return message;
}
return message.replace(new RegExp("%s", "i"), args);
}
/**
* Add / override a validator in validators list
*
* @method addValidator
* @param {String} name Validator name. Will automatically bindable through data-name=""
* @param {Function} fn Validator function. Must return {Boolean}
*/
, addValidator: function ( name, fn ) {
this.validators[ name ] = fn;
}
/**
* Add / override error message
*
* @method addMessage
* @param {String} name Message name. Will automatically be binded to validator with same name
* @param {String} message Message
*/
, addMessage: function ( key, message ) {
if ( 'type' === key ) {
this.messages[ 'type' ][ key ] = message;
return;
}
this.messages[ key ] = message;
}
}
/**
* ParsleyField class manage each form field inside a validated Parsley form.
* Returns if field valid or not depending on its value and constraints
* Manage field error display and behavior, event triggers and more
*
* @class ParsleyField
* @constructor
*/
var ParsleyField = function ( element, options, type ) {
this.options = options;
this.Validator = new Validator( options );
this.init( element, type || 'ParsleyField' );
return this;
}
ParsleyField.prototype = {
constructor: ParsleyField
/**
* Set some properties, bind constraint validators and validation events
*
* @method init
* @param {Object} element
* @param {Object} options
*/
, init: function ( element, type ) {
this.type = type;
this.isValid = true;
this.element = element;
this.validatedOnce = false;
this.$element = $( element );
this.val = this.$element.val();
this.isRequired = false;
this.constraints = [];
this.isRadioOrCheckbox = false;
// overrided by ParsleyItemMultiple if radio or checkbox input
this.hash = this.generateHash();
this.errorClassHandler = this.options.errors.classHandler( element ) || this.$element;
// a field is required if data-required="true" or class="required" or required="required"
if ( 'undefined' !== typeof this.options[ 'required' ] || this.$element.hasClass( 'required' ) || this.$element.attr( 'required' ) === 'required' ) {
this.isRequired = this.options[ 'required' ] = true;
}
// bind validators to field
this.addConstraints();
// bind parsley events if validators have been registered
if ( this.constraints.length ) {
this.bindValidationEvents();
}
}
/**
* Attach field validators functions passed through data-api
*
* @method addConstraints
*/
, addConstraints: function () {
for ( var constraint in this.options ) {
if ( 'function' === typeof this.Validator.validators[ constraint.toLowerCase() ] ) {
this.constraints.push( {
name: constraint
, requirements: this.options[ constraint ]
, isValid: null
} );
}
}
}
/**
* Bind validation events on a field
*
* @method bindValidationEvents
*/
, bindValidationEvents: function () {
this.$element.addClass( 'parsley-validated' );
// alaways bind keyup event, for better UX when a field is invalid
var triggers = this.options.trigger + ( new RegExp( "key", "i" ).test( this.options.trigger ) ? '' : ' keyup');
// force add 'change' event if async remote validator here to have result before form submitting
if ( this.options.remote ) {
triggers += new RegExp( "change", "i" ).test( triggers ) ? '' : ' change';
}
// if a validation trigger is defined
if ( triggers ) {
this.$element.on( triggers.split( ' ' ).join( '.' + this.type + ' ' ), false, $.proxy( this.eventValidation, this ) );
}
}
/**
* Hash management. Used for ul error
*
* @method generateHash
* @returns {String} 5 letters unique hash
*/
, generateHash: function () {
var text = ''
, possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for ( var i = 0; i < 5; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
}
/**
* Public getHash accessor
*
* @method generateHash
* @returns {String} hash
*/
, getHash: function () {
return this.hash;
}
/**
* Returns field val needed for validation
* Special treatment for radio & checkboxes
*
* @method getVal
* @returns {String} val
*/
, getVal: function () {
return this.$element.val();
}
/**
* Called when validation is triggered by an event
* Do nothing if val.length < this.options.validationMinlength
*
* @method eventValidation
* @param {Object} event jQuery event
*/
, eventValidation: function ( event ) {
var val = this.getVal();
// do nothing on keypress event if not explicitely passed as data-trigger and if field has no errors
if ( event.type === 'keyup' && !/keyup/i.test( this.options.trigger ) && this.isValid ) {
return true;
}
// start validation process only if field has enough chars and validation never started
if ( val.length < this.options.validationMinlength && !this.validatedOnce ) {
return true;
}
this.validate( true, false );
}
/**
* Return if field verify its constraints
*
* @method isValid
* @return {Boolean} Is field valid or not
*/
, isFieldValid: function () {
return this.validate( false, false );
}
/**
* Validate a field & display errors
*
* @method validate
* @param {Boolean} errorBubbling set to false if you just want isValid boolean without error bubbling next to fields
* @param {Boolean} async if false, wait ajax calls returns
* @return {Boolean} Is field valid or not
*/
, validate: function ( errorBubbling, async ) {
var val = this.getVal()
, isValid = null;
// do not validate a field already validated and unchanged !
if ( !this.needsValidation( val ) ) {
return this.isValid;
}
if ( this.options.listeners.onFieldValidate( this.$element ) || '' === this.val && !this.isRequired ) {
this.reset();
return null;
}
this.errorBubbling = 'undefined' !== typeof errorBubbling ? errorBubbling : true;
this.async = 'undefined' !== typeof async ? async : true;
isValid = this.applyValidators();
if ( this.errorBubbling ) {
this.manageValidationResult();
}
return isValid;
}
, needsValidation: function ( val ) {
if ( this.val === val && this.validatedOnce ) {
return false;
}
this.val = val;
return this.validatedOnce = true;
}
/**
* Loop through every fields validators
* Adds errors after unvalid fields
*
* @method applyValidators
* @return {Mixed} {Boolean} If field valid or not, null if not validated
*/
, applyValidators: function () {
var isValid = null;
for ( var constraint in this.constraints ) {
var result = this.Validator.validators[ this.constraints[ constraint ].name ]( this.val, this.constraints[ constraint ].requirements, this );
if ( false === result ) {
isValid = false;
this.constraints[ constraint ].isValid = isValid;
} else if ( true === result ) {
this.constraints[ constraint ].isValid = true;
isValid = false !== isValid;
}
}
return isValid;
}
, updateConstraint: function ( constraintName, property, value ) {
for ( var i in this.constraints ) {
if ( this.constraints[ i ].name === constraintName ) {
this.constraints[ i ][ property ] = value;
break;
}
}
}
/**
* Fired when all validators have be executed
* Returns true or false if field is valid or not
* Display errors messages below faild fields
* Adds parsley-success or parsley-error class on fields
*
* @method manageValidationResult
* @return {Boolean} Is field valid or not
*/
, manageValidationResult: function () {
var isValid = null;
for ( var constraint in this.constraints ) {
if ( false === this.constraints[ constraint ].isValid ) {
this.addError( this.constraints[ constraint ] );
this.options.listeners.onFieldError( this.$element, this.constraints[ constraint ] );
isValid = false;
} else if ( true === this.constraints[ constraint ].isValid ) {
this.removeError( this.constraints[ constraint ].name );
isValid = false !== isValid;
}
}
this.isValid = isValid;
if ( true === this.isValid ) {
this.removeErrors();
this.errorClassHandler.removeClass( this.options.errorClass ).addClass( this.options.successClass );
return true;
} else if ( false === this.isValid ) {
this.errorClassHandler.removeClass( this.options.successClass ).addClass( this.options.errorClass );
return false;
}
return isValid;
}
/**
* Remove li / ul error
*
* @method removeError
* @param {String} constraintName Method Name
*/
, removeError: function ( constraintName ) {
var liError = this.ulError + ' .' + constraintName;
// remove li error, and ul error if no more li inside
if ( this.ulError && $( liError ).remove() && $( this.ulError ).children().length === 0 ) {
$( this.ulError ).remove();
}
}
/**
* Remove all ul / li errors
*
* @method removeErrors
*/
, removeErrors: function () {
!this.ulError || $( this.ulError ).remove();
}
/**
* Remove ul errors and parsley error or success classes
*
* @method reset
*/
, reset: function () {
this.isValid = true;
this.removeErrors();
this.errorClassHandler.removeClass( this.options.successClass ).removeClass( this.options.errorClass );
}
/**
* Add li / ul errors messages
*
* @method addError
* @param {Object} constraint
*/
, addError: function ( constraint ) {
// error ul dom management done only once
if ( !this.ulError ) {
var ulId = 'parsley-' + this.hash;
this.ulError = '#' + ulId
, this.ulTemplate = $( this.options.errors.errorsWrapper ).attr( 'id', ulId ).addClass( 'parsley-error-list' );
}
// TODO: refacto error name w/ proper & readable function
var constraintName = constraint.name
, liError = this.ulError + ' .' + constraintName
, liTemplate = $( this.options.errors.errorElem ).addClass( constraintName )
, message = constraint.name === 'type' ?
this.Validator.messages[ constraintName ][ constraint.requirements ] : ( 'undefined' === typeof this.Validator.messages[ constraintName ] ?
this.Validator.messages.defaultMessage : this.Validator.formatMesssage( this.Validator.messages[ constraintName ], constraint.requirements ) );
if ( !$( this.ulError ).length ) {
this.options.errors.container( this.element, this.ulTemplate, this.isRadioOrCheckbox )
|| !this.isRadioOrCheckbox ? this.$element.after( this.ulTemplate ) : this.$element.parent().after( this.ulTemplate );
}
if ( !$( liError ).length ) {
$( this.ulError ).append( $( liTemplate ).text( message ) );
}
}
/**
* Add custom listeners
*
* @param {Object} { listener: function () {} }, eg { onFormSubmit: function ( isValid, event, focus ) { ... } }
*/
, addListener: function ( object ) {
for ( var listener in object ) {
this.options.listeners[ listener ] = object[ listener ];
}
}
}
/**
* ParsleyFieldMultiple override ParsleyField for checkbox and radio inputs
* Pseudo-heritance to manage divergent behavior from ParsleyItem in dedicated methods
*
* @class ParsleyFieldMultiple
* @constructor
*/
var ParsleyFieldMultiple = function ( element, options ) {
this.initMultiple( element, options );
this.inherit( element, options );
}
ParsleyFieldMultiple.prototype = {
constructor: ParsleyFieldMultiple
/**
* Set some specific properties, call some extra methods to manage radio / checkbox
*
* @method init
* @param {Object} element
* @param {Object} options
*/
, initMultiple: function ( element, options ) {
this.element = element;
this.$element = $( element );
this.hash = this.getName();
this.isRadioOrCheckbox = true;
this.isRadio = this.$element.is( 'input[type=radio]' );
this.isCheckbox = this.$element.is( 'input[type=checkbox]' );
this.siblings = 'input[name="' + this.$element.attr( 'name' ) + '"]';
this.$siblings = $( this.siblings );
this.errorClassHandler = options.errors.classHandler( element ) || this.$element.parent();
}
/**
* Set specific constraints messages, do pseudo-heritance
*
* @method inherit
* @param {Object} element
* @param {Object} options
*/
, inherit: function ( element, options ) {
var messages = {
mincheck: "You must select at least %s choices."
, maxcheck: "You must select %s choices or less."
, rangecheck: "You must select between %s and %s choices."
}
, options = $.extend(true, {}, { messages: messages }, options )
, clone = new ParsleyField( element, options );
for ( var property in clone ) {
if ( 'undefined' === typeof this[ property ] ) {
this[ property ] = clone [ property ];
}
}
}
/**
* Set specific constraints messages, do pseudo-heritance
*
* @method getName
* @returns {String} radio / checkbox hash is cleaned "name" property
*/
, getName: function () {
return this.$element.attr( 'name' ).replace( /(:|\.|\[|\])/g, '' );
}
/**
* Special treatment for radio & checkboxes
* Returns checked radio or checkboxes values
*
* @method getVal
* @returns {String} val
*/
, getVal: function () {
if ( this.isRadio ) {
return $( this.siblings + ':checked' ).val() || '';
}
if ( this.isCheckbox ) {
var values = [];
$( this.siblings + ':checked' ).each( function () {
values.push( $( this ).val() );
} )
return values;
}
}
}
/**
* ParsleyForm class manage Parsley validated form.
* Manage its fields and global validation
*
* @class ParsleyForm
* @constructor
*/
var ParsleyForm = function ( element, options ) {
this.init( 'parsleyForm', element, options );
}
ParsleyForm.prototype = {
constructor: ParsleyForm
/* init data, bind jQuery on() actions */
, init: function ( type, element, options ) {
this.type = type;
this.items = [];
this.$element = $( element );
this.options = options;
var self = this;
this.$element.find( options.inputs ).each( function () {
$( this ).parsley( options );
self.items.push( $( this ) );
});
this.$element.on( 'submit' , false, $.proxy( this.validate, this ) );
}
/**
* Add custom listeners
*
* @param {Object} { listener: function () {} }, eg { onFormSubmit: function ( isValid, event, focus ) { ... } }
*/
, addListener: function ( object ) {
for ( var listener in object ) {
if ( new RegExp( 'Field' ).test( listener ) ) {
for ( var item in this.items ) {
this.items[ item ].parsley( 'addListener', object );
}
} else {
this.options[ listener ] = object[ listener ];
}
}
}
/**
* Process each form field validation
* Display errors, call custom onFormSubmit() function
*
* @method validate
* @param {Object} event jQuery Event
* @return {Boolean} Is form valid or not
*/
, validate: function ( event ) {
var isValid = true
, focusedField = false;
for ( var item in this.items ) {
if ( false === this.items[ item ].parsley( 'validate' ) ) {
isValid = false;
if ( !focusedField && 'first' === this.options.focus || 'last' === this.options.focus ) {
focusedField = this.items[ item ];
}
}
}
// form is invalid, focus an error field depending on focus policy
if ( !isValid ) {
focusedField.focus();
}
this.options.listeners.onFormSubmit( isValid, event, focusedField );
return isValid;
}
/**
* Remove all errors ul under invalid fields
*
* @method removeErrors
*/
, removeErrors: function () {
for ( var item in this.items ) {
this.items[ item ].parsley( 'reset' );
}
}
}
/**
* Parsley plugin definition
* Provides an interface to access public Validator, ParsleyForm and ParsleyField functions
*
* @class Parsley
* @constructor
* @param {Mixed} Options. {Object} to configure Parsley or {String} method name to call a public class method
* @param {Function} Callback function
* @return {Mixed} public class method return
*/
$.fn.parsley = function ( option, fn ) {
var options = $.extend(true, {}, $.fn.parsley.defaults, option, this.data() )
, returnValue = null;
function bind ( self, type ) {
var data = $( self ).data( type );
// if data never binded or we want to clone a build (for radio & checkboxes), bind it right now!
if ( !data ) {
switch ( type ) {
case 'parsleyForm':
data = new ParsleyForm( self, options );
break;
case 'parsleyField':
data = new ParsleyField( self, options );
break;
case 'parsleyFieldMultiple':
data = new ParsleyFieldMultiple( self, options );
break;
default:
return;
}
$( self ).data( type, data );
}
// here is our parsley public function accessor
if ( 'string' === typeof option && 'function' === typeof data[ option ] ) {
return data[ option ]( fn );
}
}
// if a form elem is given, bind all its input children
if ( $( this ).is( 'form' ) ) {
returnValue = bind ( $( this ), 'parsleyForm' );
// if it is a Parsley supported single element, bind it too, except inputs type hidden
// add here a return instance, cuz' we could call public methods on single elems with data[ option ]() above
} else if ( $( this ).is( options.inputs ) && !$( this ).is( options.excluded ) ) {
returnValue = bind( $( this ), !$( this ).is( 'input[type=radio], input[type=checkbox]' ) ? 'parsleyField' : 'parsleyFieldMultiple' );
}
return 'function' === typeof fn ? fn() : returnValue;
}
$.fn.parsley.Constructor = ParsleyForm;
/**
* Parsley plugin configuration
*
* @property $.fn.parsley.defaults
* @type {Object}
*/
$.fn.parsley.defaults = {
// basic data-api overridable properties here..
inputs: 'input, textarea, select' // Default supported inputs.
, excluded: 'input[type=hidden]' // Do not validate input[type=hidded].
, trigger: false // $.Event() that will trigger validation. eg: keyup, change..
, focus: 'first' // 'fist'|'last'|'none' which error field would have focus first on form validation
, validationMinlength: 3 // If trigger validation specified, only if value.length > validationMinlength
, successClass: 'parsley-success' // Class name on each valid input
, errorClass: 'parsley-error' // Class name on each invalid input
, validators: {} // Add your custom validators functions
, messages: {} // Add your own error messages here
//some quite advanced configuration here..
, errors: {
classHandler: function ( elem ) {} // class is directly set on elem, parent for radio/checkboxes
, container: function ( elem, template, isRadioOrCheckbox ) {} // error ul is inserted after elem, parent for radio/checkboxes
, errorsWrapper: '<ul></ul>' // do not set an id for this elem, it would have an auto-generated id
, errorElem: '<li></li>' // each field constraint fail in an li
}
, listeners: {
onFieldValidate: function ( elem ) { return false; } // Return true to ignore field validation
, onFormSubmit: function ( isFormValid, event, focusedField ) {} // Executed once on form validation
, onFieldError: function ( field, constraint ) {} // Executed when a field is detected as invalid
}
}
/* PARSLEY auto-bind DATA-API
* ======================== */
$( window ).on( 'load', function () {
$( '[data-validate="parsley"]' ).each( function () {
$( this ).parsley();
})
});
// This plugin works with jQuery or Zepto (with data extension builded for Zepto.)
}(window.jQuery || window.Zepto);