forked from victorjonsson/jQuery-Form-Validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.formvalidator.js
executable file
·963 lines (833 loc) · 34.1 KB
/
jquery.formvalidator.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
/*
* FORM VALIDATION MADE EASY
* ------------------------------------------
* Created by Victor Jonsson <http://www.victorjonsson.se>
* Documentation and issue tracking on Github <https://github.com/victorjonsson/jQuery-Form-Validator/>
*
* Dual licensed under the MIT or GPL Version 2 licenses
*
* $version 1.3
*/
(function($) {
$.extend($.fn, {
/**
* Should be called on the element containing the input elements
*
* @param {Object} language Optional, will override jQueryFormUtils.LANG
* @param {Object} settings Optional, will override the default settings
* @return {jQuery}
*/
validateOnBlur : function(language, settings) {
$(this).find('textarea,input').blur(function() {
$(this).doValidate(language, settings);
});
return $(this);
},
/**
* Should be called on the element containing the input elements.
* <input data-help="The info that I want to display for the user when input is focused" ... />
*
* @param {String} attrName Optional, default is data-help
* @return {jQuery}
*/
showHelpOnFocus : function(attrName) {
if(!attrName) {
attrName = 'data-help';
}
$(this).find('textarea,input').each(function() {
var help = $(this).attr(attrName);
if(help) {
$(this)
.focus(function() {
var $element = $(this);
if($element.parent().find('.jquery_form_help').length == 0) {
$element.after(
$('<span />')
.addClass('jquery_form_help')
.text(help)
.hide()
.fadeIn()
);
}
})
.blur(function() {
$(this).parent().find('.jquery_form_help')
.fadeOut('slow', function() {
$(this).remove();
});
});
}
});
return $(this);
},
/**
* Function that validates the value of given input and shows
* error message in a span element that is appended to the parent
* element
*
* @param {Object} language Optional, will override jQueryFormUtils.LANG
* @param {Object} settings Optional, will override the default settings
* @param {Boolean} attachKeyupEvent Optional
* @return {jQuery}
*/
doValidate : function(language, settings, attachKeyupEvent) {
if(typeof attachKeyupEvent == 'undefined') {
attachKeyupEvent = true;
}
var $element = $(this);
var config = {
validationRuleAttribute : 'data-validation',
validationErrorMsgAttribute : 'data-validation-error-msg', // define custom err msg inline with element
errorElementClass : 'error', // Class that will be put on elements which value is invalid
borderColorOnError : 'red',
dateFormat : 'yyyy-mm-dd'
};
if (settings) {
$.extend(config, settings);
}
if (language) {
$.extend(jQueryFormUtils.LANG,language);
}
// get updated dialog strings
language = jQueryFormUtils.LANG;
var elementType = $element.attr('type');
if (jQueryFormUtils.defaultBorderColor === null && elementType !== 'submit' && elementType !== 'checkbox' && elementType !== 'radio') {
jQueryFormUtils.defaultBorderColor = $element.css('border-color');
}
// Remove possible error style applied by previous validation
$element
.removeClass(config.errorElementClass)
.parent()
.find('.jquery_form_error_message').remove();
if(config.borderColorOnError !== '') {
$element.css('border-color', jQueryFormUtils.defaultBorderColor);
}
var validation = jQueryFormUtils.validateInput($element, language, config);
if(validation === true) {
$element.unbind('keyup');
} else {
$element
.addClass(config.errorElementClass)
.parent()
.append('<span class="jquery_form_error_message">'+validation+'</span>');
if(config.borderColorOnError !== '') {
$element.css('border-color', config.borderColorOnError);
}
if(attachKeyupEvent) {
$element.bind('keyup', function() {
$(this).doValidate(language, settings, false);
});
}
}
return $(this);
},
/**
* Function that validate all inputs in a form
*
* @param language
* @param settings
*/
validate : function(language, settings) {
/*
* Config
*/
var config = {
ignore : [], // Names of inputs not to be validated even though node attribute containing the validation rules tells us to
errorElementClass : 'error', // Class that will be put on elements which value is invalid
borderColorOnError : 'red', // Border color of elements which value is invalid, empty string to not change border color
errorMessageClass : 'jquery_form_error_message', // class name of div containing error messages when validation fails
validationRuleAttribute : 'data-validation', // name of the attribute holding the validation rules
validationErrorMsgAttribute : 'data-validation-error-msg', // define custom err msg inline with element
errorMessagePosition : 'top', // Can be either "top" or "element"
scrollToTopOnError : true,
dateFormat : 'yyyy-mm-dd'
};
/*
* Extends initial settings
*/
if (settings) {
$.extend(config, settings);
}
if (language) {
$.extend(jQueryFormUtils.LANG, language);
}
// get updated dialog strings
language = jQueryFormUtils.LANG;
/**
* Tells whether or not to validate element with this name and of this type
*
* @param {String} name
* @param {String} type
* @return {Boolean}
*/
var ignoreInput = function(name, type) {
if (type === 'submit' || type === 'button') {
return true;
}
for (var i = 0; i < config.ignore.length; i++) {
if (config.ignore[i] === name) {
return true;
}
}
return false;
};
/**
* Adds message to error message stack if not already in the message stack
*
* @param {String} mess
*/
var addErrorMessage = function(mess) {
if (jQuery.inArray(mess, errorMessages) < 0) {
errorMessages.push(mess);
}
};
/** Error messages for this validation */
var errorMessages = [];
/** Input elements which value was not valid */
var errorInputs = [];
/** Form instance */
var $form = $(this);
//
// Validate radio buttons
//
$form.find('input[type=radio]').each(function() {
var validationRule = $(this).attr(config.validationRuleAttribute);
if (typeof validationRule != 'undefined' && validationRule === 'required') {
var radioButtonName = $(this).attr('name');
var isChecked = false;
$form.find('input[name=' + radioButtonName + ']').each(function() {
if ($(this).is(':checked')) {
isChecked = true;
}
});
if (!isChecked) {
errorMessages.push(language.requiredFields);
errorInputs.push($(this));
$(this).attr('data-error', language.requiredFields);
}
}
});
//
// Validate element values
//
$form.find('input,textarea,select').each(function() {
if (!ignoreInput($(this).attr('name'), $(this).attr('type'))) {
// memorize border color
if (jQueryFormUtils.defaultBorderColor === null && $(this).attr('type')) {
jQueryFormUtils.defaultBorderColor = $(this).css('border-color');
}
var valid = jQueryFormUtils.validateInput(
$(this),
language,
config,
$form
);
if(valid !== true) {
errorInputs.push($(this));
$(this).attr('data-error', valid);
addErrorMessage(valid);
}
}
});
//
// Reset style and remove error class
//
$form.find('input,textarea,select')
.css('border-color', jQueryFormUtils.defaultBorderColor)
.removeClass(config.errorElementClass);
//
// Remove possible error messages from last validation
//
$('.' + config.errorMessageClass).remove();
$('.jquery_form_error_message').remove();
//
// Validation failed
//
if (errorInputs.length > 0) {
// Apply error style to invalid inputs
for (var i = 0; i < errorInputs.length; i++) {
if (config.borderColorOnError !== '') {
errorInputs[i].css('border-color', config.borderColorOnError);
}
errorInputs[i].addClass(config.errorElementClass);
}
// display all error messages in top of form
if (config.errorMessagePosition === 'top') {
var messages = '<strong>' + language.errorTitle + '</strong>';
for (var i = 0; i < errorMessages.length; i++) {
messages += '<br />* ' + errorMessages[i];
}
$form.children().eq(0).before('<p class="' + config.errorMessageClass + '">' + messages + '</p>');
if(config.scrollToTopOnError) {
$(window).scrollTop($form.offset().top - 20);
}
}
// Display error message below input field
else {
for (var i = 0; i < errorInputs.length; i++) {
var parent = errorInputs[i].parent();
var errorSpan = parent.find('span[class=jquery_form_error_message]');
if (errorSpan.length > 0) {
errorSpan.eq(0).text(errorInputs[i].attr('data-error'));
} else {
parent.append('<span class="jquery_form_error_message">' + errorInputs[i].attr('data-error') + '</span>');
}
}
}
return false;
}
return true;
},
/**
* Plugin for displaying input length restriction
*/
restrictLength : function(maxLengthElement) {
new jQueryFormUtils.lengthRestriction(this, maxLengthElement);
return this;
}
});
})(jQuery);
/**
* Namespace for helper functions
*/
var jQueryFormUtils = {};
/**
* Static variable for holding default border color on input
*/
jQueryFormUtils.defaultBorderColor = null;
/**
* Validate email
*
* @return {Boolean}
*/
jQueryFormUtils.validateEmail = function(email) {
var emailFilter = /^([a-zA-Z0-9_\.\-])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(emailFilter.test(email)) {
var parts = email.split('@');
if(parts.length == 2) {
return jQueryFormUtils.validateDomain(parts[1]);
}
}
return false;
};
/**
* Validate phone number, at least 7 digits only one hyphen and plus allowed
*
* @return {Boolean}
*/
jQueryFormUtils.validatePhoneNumber = function(tele) {
var numPlus = tele.match(/\+/g);
var numHifen = tele.match(/-/g);
if ((numPlus !== null && numPlus.length > 1) || (numHifen !== null && numHifen.length > 1)) {
return false;
}
if (numPlus !== null && tele.indexOf('+') !== 0) {
return false;
}
tele = tele.replace(/([-|\+])/g, '');
return tele.length > 8 && tele.match(/[^0-9]/g) === null;
};
/**
* Validate that string is a swedish telephone number
*
* @param {Number}
* @return {Boolean}
*/
jQueryFormUtils.validateSwedishMobileNumber = function(number) {
if (!jQueryFormUtils.validatePhoneNumber(number)) {
return false;
}
number = number.replace(/[^0-9]/g, '');
var begin = number.substring(0, 3);
if (number.length != 10 && begin !== '467') {
return false;
} else if (number.length != 11 && begin === '467') {
return false;
}
return (/07[0-9{1}]/).test(begin) || (begin === '467' && number.substr(3, 1) === '0');
};
/**
* Validate that string is a UK VAT Number
* TODO: Extra Checking for other VAT Numbers (Other countries and UK Government/Health Authorities)
* Code Adapted from http://www.codingforums.com/showthread.php?t=211967
*
* @param {Number}
* @return {Boolean}
*/
jQueryFormUtils.validateUKVATNumber = function(number) {
number = number.replace(/[^0-9]/g, '');
//Check Length
if(number.length < 9) {
return false;
}
var valid = false;
var VATsplit = [];
VATsplit = number.split("");
var checkDigits = Number(VATsplit[7] + VATsplit[8]); // two final digits as a number
var firstDigit = VATsplit[0];
var secondDigit = VATsplit[1];
if ((firstDigit == 0) && (secondDigit >0)) {
return false;
}
var total = 0;
for (var i=0; i<7; i++) { // first 7 digits
total += VATsplit[i] * (8-i); // sum weighted cumulative total
}
var c = 0;
var i = 0;
for (var m = 8; m>=2; m--) {
c += VATsplit[i] * m;
i++;
}
// Traditional Algorithm for VAT numbers issued before 2010
while (total > 0) {
total -= 97; // deduct 97 repeatedly until total is negative
}
total = Math.abs(total); // make positive
if (checkDigits == total) {
valid = true;
}
// If not valid try the new method (introduced November 2009) by subtracting 55 from the mod 97 check digit if we can - else add 42
if (!valid) {
total = total%97 // modulus 97
if (total >= 55) {
total = total - 55
} else {
total = total + 42
}
if (total == checkDigits) {
valid = true;
}
}
return valid;
};
/**
* Is this a valid birth date YYYY-MM-DD
*
* @return {Boolean}
*/
jQueryFormUtils.validateBirthdate = function(val, dateFormat) {
var inputDate = this.parseDate(val, dateFormat);
if (!inputDate) {
return false;
}
var d = new Date();
var currentYear = d.getFullYear();
var year = inputDate[0];
var month = inputDate[1];
var day = inputDate[2];
if (year === currentYear) {
var currentMonth = d.getMonth() + 1;
if (month === currentMonth) {
var currentDay = d.getDate();
return day <= currentDay;
}
else {
return month < currentMonth;
}
}
else {
return year < currentYear && year > (currentYear - 124); // we can not live for ever yet...
}
};
/**
* Is it a correct date according to given dateFormat. Will return false if not, otherwise
* an array 0=>year 1=>month 2=>day
*
* @param {String} val
* @param {String} dateFormat
* @return {Array}|{Boolean}
*/
jQueryFormUtils.parseDate = function(val, dateFormat) {
var divider = dateFormat.replace(/[a-zA-Z]/gi, '').substring(0,1);
var regexp = '^';
var formatParts = dateFormat.split(divider);
for(var i=0; i < formatParts.length; i++) {
regexp += (i > 0 ? '\\'+divider:'') + '(\\d{'+formatParts[i].length+'})';
}
regexp += '$';
var matches = val.match(new RegExp(regexp));
if (matches === null) {
return false;
}
var findDateUnit = function(unit, formatParts, matches) {
for(var i=0; i < formatParts.length; i++) {
if(formatParts[i].substring(0,1) === unit) {
return jQueryFormUtils.parseDateInt(matches[i+1]);
}
}
return -1;
};
var month = findDateUnit('m', formatParts, matches);
var day = findDateUnit('d', formatParts, matches);
var year = findDateUnit('y', formatParts, matches);
if ((month === 2 && day > 28 && (year % 4 !== 0 || year % 100 === 0 && year % 400 !== 0))
|| (month === 2 && day > 29 && (year % 4 === 0 || year % 100 !== 0 && year % 400 === 0))
|| month > 12 || month === 0) {
return false;
}
if ((this.isShortMonth(month) && day > 30) || (!this.isShortMonth(month) && day > 31) || day === 0) {
return false;
}
return [year, month, day];
};
/**
* skum fix. är talet 05 eller lägre ger parseInt rätt int annars får man 0 när man kör parseInt?
*
* @param {String} val
* @param {Number}
*/
jQueryFormUtils.parseDateInt = function(val) {
if (val.indexOf('0') === 0) {
val = val.replace('0', '');
}
return parseInt(val,10);
};
/**
* Validate swedish security number yyymmddXXXX
*
* @param {String} securityNumber
* @return {Boolean}
*/
jQueryFormUtils.validateSwedishSecurityNumber = function(securityNumber) {
if (!securityNumber.match(/^(\d{4})(\d{2})(\d{2})(\d{4})$/)) {
return false;
}
var year = RegExp.$1;
var month = jQueryFormUtils.parseDateInt(RegExp.$2);
var day = jQueryFormUtils.parseDateInt(RegExp.$3);
// var gender = parseInt( (RegExp.$4) .substring(2,3)) % 2; ==> 1 === male && 0 === female
var months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if (year % 400 === 0 || year % 4 === 0 && year % 100 !== 0) {
months[1] = 29;
}
if (month < 1 || month > 12 || day < 1 || day > months[month - 1]) {
return false;
}
securityNumber = securityNumber.substring(2, securityNumber.length);
var check = '';
for (var i = 0; i < securityNumber.length; i++) {
check += ((((i + 1) % 2) + 1) * securityNumber.substring(i, i + 1));
}
var checksum = 0;
for (i = 0; i < check.length; i++) {
checksum += parseInt(check.substring(i, i + 1),10);
}
return checksum % 10 === 0;
};
/**
* Validate time HH:mm
*
* @param {String} time
* @return {Boolean}
*/
jQueryFormUtils.validateTime = function(time) {
if (time.match(/^(\d{2}):(\d{2})$/) === null) {
return false;
} else {
var hours = parseInt(time.split(':')[0],10);
var minutes = parseInt(time.split(':')[1],10);
if((hours > 24 || minutes > 59) || (hours === 24 && minutes > 0)) {
return false;
}
}
return true;
};
/**
* Validate float value
*
* @param {String} val
* @return {Boolean}
*/
jQueryFormUtils.validateFloat = function(val) {
return val.match(/^(\-|)([0-9]+)\.([0-9]+)$/) !== null;
};
/**
* Validate that given value is a number
*
* @param {String} val
* @return {Boolean}
*/
jQueryFormUtils.validateInteger = function(val) {
return val !== '' && val.replace(/[0-9]/g, '') === '';
};
/**
* Has month only 30 days?
*
* @param {Number} m
* @return {Boolean}
*/
jQueryFormUtils.isShortMonth = function(m) {
return (m % 2 === 0 && m < 7) || (m % 2 !== 0 && m > 7);
};
/**
* Simple spam check
*
* @param {String} val
* @param {String} classAttr
* @return {Boolean}
*/
jQueryFormUtils.simpleSpamCheck = function(val, classAttr) {
var answer = classAttr.match(/captcha([0-9a-z]+)/i)[1].replace('captcha', '');
return val === answer;
};
/**
* Validate domain name
*
* @param {String} val
* @return {Boolean}
*/
jQueryFormUtils.validateDomain = function(val) {
val = val.replace('ftp://', '').replace('https://', '').replace('http://', '').replace('www.', '');
var arr = new Array('.com', '.net', '.org', '.biz', '.coop', '.info', '.museum', '.name', '.pro',
'.edu', '.gov', '.int', '.mil', '.ac', '.ad', '.ae', '.af', '.ag', '.ai', '.al',
'.am', '.an', '.ao', '.aq', '.ar', '.as', '.at', '.au', '.aw', '.az', '.ba', '.bb',
'.bd', '.be', '.bf', '.bg', '.bh', '.bi', '.bj', '.bm', '.bn', '.bo', '.br', '.bs',
'.bt', '.bv', '.bw', '.by', '.bz', '.ca', '.cc', '.cd', '.cf', '.cg', '.ch', '.ci',
'.ck', '.cl', '.cm', '.cn', '.co', '.cr', '.cu', '.cv', '.cx', '.cy', '.cz', '.de',
'.dj', '.dk', '.dm', '.do', '.dz', '.ec', '.ee', '.eg', '.eh', '.er', '.es', '.et',
'.fi', '.fj', '.fk', '.fm', '.fo', '.fr', '.ga', '.gd', '.ge', '.gf', '.gg', '.gh',
'.gi', '.gl', '.gm', '.gn', '.gp', '.gq', '.gr', '.gs', '.gt', '.gu', '.gv', '.gy',
'.hk', '.hm', '.hn', '.hr', '.ht', '.hu', '.id', '.ie', '.il', '.im', '.in', '.io',
'.iq', '.ir', '.is', '.it', '.je', '.jm', '.jo', '.jp', '.ke', '.kg', '.kh', '.ki',
'.km', '.kn', '.kp', '.kr', '.kw', '.ky', '.kz', '.la', '.lb', '.lc', '.li', '.lk',
'.lr', '.ls', '.lt', '.lu', '.lv', '.ly', '.ma', '.mc', '.md', '.mg', '.mh', '.mk',
'.ml', '.mm', '.mn', '.mo', '.mp', '.mq', '.mr', '.ms', '.mt', '.mu', '.mv', '.mw',
'.mx', '.my', '.mz', '.na', '.nc', '.ne', '.nf', '.ng', '.ni', '.nl', '.no', '.np',
'.nr', '.nu', '.nz', '.om', '.pa', '.pe', '.pf', '.pg', '.ph', '.pk', '.pl', '.pm',
'.pn', '.pr', '.ps', '.pt', '.pw', '.py', '.qa', '.re', '.ro', '.rw', '.ru', '.sa',
'.sb', '.sc', '.sd', '.se', '.sg', '.sh', '.si', '.sj', '.sk', '.sl', '.sm', '.sn',
'.so', '.sr', '.st', '.sv', '.sy', '.sz', '.tc', '.td', '.tf', '.tg', '.th', '.tj',
'.tk', '.tm', '.tn', '.to', '.tp', '.tr', '.tt', '.tv', '.tw', '.tz', '.ua', '.ug',
'.uk', '.um', '.us', '.uy', '.uz', '.va', '.vc', '.ve', '.vg', '.vi', '.vn', '.vu',
'.ws', '.wf', '.ye', '.yt', '.yu', '.za', '.zm', '.zw', '.mobi', '.xxx');
var dot = val.lastIndexOf('.');
var domain = val.substring(0, dot);
var ext = val.substring(dot, val.length);
var hasTopDomain = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === ext) {
if(ext==='.uk') {
//Run Extra Checks for UK Domain Names
var domainParts = val.split('.');
var tld2 = domainParts[domainParts.length-2];
var ukarr = new Array('co', 'me', 'ac', 'gov', 'judiciary',
'ltd', 'mod', 'net', 'nhs', 'nic', 'org', 'parliament',
'plc', 'police', 'sch', 'bl', 'british-library', 'jet',
'nls');
for(var j = 0; j < ukarr.length; j++) {
if(ukarr[j] === tld2) {
hasTopDomain = true;
break;
}
}
} else {
hasTopDomain = true;
break;
}
}
}
if (!hasTopDomain) {
return false;
} else if (dot < 2 || dot > 57) {
return false;
} else {
var firstChar = domain.substring(0, 1);
var lastChar = domain.substring(domain.length - 1, domain.length);
if (firstChar === '-' || firstChar === '.' || lastChar === '-' || lastChar === '.') {
return false;
}
if (domain.split('.').length > 3 || domain.split('..').length > 1) {
return false;
}
if (domain.replace(/[0-9a-z\.\-]/g, '') !== '') {
return false;
}
}
return true;
};
/**
* Validate the value of given element according to the validation rule
* defined in attribute with given name. Will return true if valid,
* error message otherwise
*
* @param {jQuery} el
* @param {Object} language (jQueryFormUtils.LANG)
* @param {String} validationRuleAttr
* @param {jQuery} form
* @return {String}|{Boolean}
*/
jQueryFormUtils.validateInput = function(el, language, config, form) {
var value = jQuery.trim(el.val());
var validationRules = el.attr(config.validationRuleAttribute);
// see if form element has inline err msg attribute
var validationErrorMsg = el.attr(config.validationErrorMsgAttribute);
if (typeof validationRules != 'undefined' && validationRules !== null) {
/**
* <input data-validation="length12" /> => getAttribute($(element).attr('class'), 'length') = 12
* @param {String} attrValue
* @param {String} attrName
* @returns integer
*/
var getAttributeInteger = function(attrValue, attrName) {
var regex = new RegExp('(' + attrName + '[0-9\-]+)', "g");
return attrValue.match(regex)[0].replace(/[^0-9\-]/g, '');
};
// Required
if (validationRules.indexOf('required') > -1 && value === '') {
// return custom inline err msg if defined
return validationErrorMsg || language.requiredFields;
}
// Min length
if (validationRules.indexOf('validate_min_length') > -1 && value.length < getAttributeInteger(validationRules, 'length')) {
return validationErrorMsg || language.tooShortStart + getAttributeInteger(validationRules, 'length') + language.tooShortEnd;
}
// Max length
if (validationRules.indexOf('validate_max_length') > -1 && value.length > getAttributeInteger(validationRules, 'length')) {
return validationErrorMsg || language.tooLongStart + getAttributeInteger(validationRules, 'length') + language.tooLongEnd;
}
// Length range
if (validationRules.indexOf('validate_length') > -1) {
var range = getAttributeInteger(validationRules, 'length').split('-');
if (value.length < parseInt(range[0],10) || value.length > parseInt(range[1],10)) {
return validationErrorMsg || language.badLength + getAttributeInteger(validationRules, 'length') + language.tooLongEnd;
}
}
// Email
if (validationRules.indexOf('validate_email') > -1 && !jQueryFormUtils.validateEmail(value)) {
return validationErrorMsg || language.badEmail;
}
// Domain
else if (validationRules.indexOf('validate_domain') > -1 && !jQueryFormUtils.validateDomain(value)) {
return validationErrorMsg || language.badDomain;
}
// Url
else if (validationRules.indexOf('validate_url') > -1 && !jQueryFormUtils.validateUrl(value)) {
return validationErrorMsg || language.badUrl;
}
// Float
else if (validationRules.indexOf('validate_float') > -1 && !jQueryFormUtils.validateFloat(value)) {
return validationErrorMsg || language.badFloat;
}
// Integer
else if (validationRules.indexOf('validate_int') > -1 && !jQueryFormUtils.validateInteger(value)) {
return validationErrorMsg || language.badInt;
}
// Time
else if (validationRules.indexOf('validate_time') > -1 && !jQueryFormUtils.validateTime(value)) {
return validationErrorMsg || language.badTime;
}
// Date
else if (validationRules.indexOf('validate_date') > -1 && !jQueryFormUtils.parseDate(value, config.dateFormat)) {
return validationErrorMsg || language.badDate;
}
// Birth date
else if (validationRules.indexOf('validate_birthdate') > -1 && !jQueryFormUtils.validateBirthdate(value, config.dateFormat)) {
return validationErrorMsg || language.badDate;
}
// Phone number
else if (validationRules.indexOf('validate_phone') > -1 && !jQueryFormUtils.validatePhoneNumber(value)) {
return validationErrorMsg || language.badTelephone;
}
// Swedish phone number
else if (validationRules.indexOf('validate_swemobile') > -1 && !jQueryFormUtils.validateSwedishMobileNumber(value)) {
return validationErrorMsg || language.badTelephone;
}
// simple spam check
else if (validationRules.indexOf('validate_spamcheck') > -1 && !jQueryFormUtils.simpleSpamCheck(value, validationRules)) {
return validationErrorMsg || language.badSecurityAnswer;
}
// UK VAT Number check
else if (validationRules.indexOf('validate_ukvatnumber') > -1 && !jQueryFormUtils.validateUKVATNumber(value)) {
return validationErrorMsg || language.badUKVatAnswer;
}
// Custom regexp validation
if (validationRules.indexOf('validate_custom') > -1 && validationRules.indexOf('regexp/') > -1) {
var regexp = new RegExp(validationRules.split('regexp/')[1].split('/')[0]);
if (!regexp.test(value)) {
return validationErrorMsg || language.badCustomVal;
}
}
// Swedish social security number
if (validationRules.indexOf('validate_swesc') > -1 && !jQueryFormUtils.validateSwedishSecurityNumber(value)) {
return validationErrorMsg || language.badSecurityNumber;
}
// confirmation
if (validationRules.indexOf('validate_confirmation') > -1 && typeof(form) != 'undefined') {
var conf = '';
var confInput = form.find('input[name=' + el.attr('name') + '_confirmation]').eq(0);
if (confInput) {
conf = confInput.val();
}
if (value !== conf) {
return validationErrorMsg || language.notConfirmed;
}
}
}
return true;
};
/**
* Error dialogs
*
* @var {Object}
*/
jQueryFormUtils.LANG = {
errorTitle : 'Form submission failed!',
requiredFields : 'You have not answered all required fields',
badTime : 'You have not given a correct time',
badEmail : 'You have not given a correct e-mail address',
badTelephone : 'You have not given a correct phone number',
badSecurityAnswer : 'You have not given a correct answer to the security question',
badDate : 'You have not given a correct date',
tooLongStart : 'You have given an answer longer than ',
tooLongEnd : ' characters',
tooShortStart : 'You have given an answer shorter than ',
tooShortEnd : ' characters',
badLength : 'You have to give an answer between ',
notConfirmed : 'Values could not be confirmed',
badDomain : 'Incorrect domain value',
badUrl : 'Incorrect url value',
badFloat : 'Incorrect float value',
badCustomVal : 'You gave an incorrect answer',
badInt : 'Incorrect integer value',
badSecurityNumber : 'Your social security number was incorrect',
badUKVatAnswer : 'Incorrect UK VAT Number'
};
/**
* Validate url
*
* @param {String} url
* @return {Boolean}
*/
jQueryFormUtils.validateUrl = function(url) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ but added support for arrays in the url ?arg[]=sdfsdf
var urlFilter = /^(https|http|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;
if(urlFilter.test(url)) {
var domain = url.split(/^https|^http|^ftp/i)[1].replace('://', '');
var domainSlashPos = domain.indexOf('/');
if(domainSlashPos > -1)
domain = domain.substr(0, domainSlashPos);
return jQueryFormUtils.validateDomain(domain); // todo: add support for IP-addresses
}
return false;
};
/**
* Restrict input length
*
* @param {jQuery} inputElement Jquery Html object
* @param {jQuery} maxLengthElement jQuery Html Object
* @return void
*/
jQueryFormUtils.lengthRestriction = function(inputElement, maxLengthElement) {
this.input = inputElement;
this.maxLength = parseInt(maxLengthElement.text(),10);
var self = this;
$(this.input).keyup(function() {
$(this).val($(this).val().substring(0, self.maxLength));
maxLengthElement.text(self.maxLength - $(this).val().length);
})
.focus(function() {
$(this).keyup();
})
.trigger('keyup');
};