forked from davidnguyen/bootstrap-validate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.validate.js
77 lines (74 loc) · 3.05 KB
/
bootstrap.validate.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
/*
* Bootstrap Validate Scriptlet that supports Twitter Bootstrap styling to
* jQuery validate and unobstrusive jQuery validate
* Author: David Nguyen ([email protected])
*/
(function ($) {
var elements = {
fieldValidationSpanAll: 'span.field-validation-valid, span.field-validation-error',
fieldValidationSpanError: 'span.field-validation-error',
inputValidationError: '.input-validation-error',
controlGroupDiv: 'div.form-group',
form: 'form',
formInput: 'form input, form select, form textarea'
},
classes = {
inlineHelp: 'help-inline',
error: 'has-error'
},
addInlineHelp = function () {
/// <summary>Adds inline-help classes</summary>
$(this).addClass(classes.inlineHelp);
},
onFormSubmit = function () {
/// <summary>Handles form submit event</summary>
if ($(this).valid()) {
$(this).find(elements.controlGroupDiv).each(function () {
if ($(this).find(elements.inputValidationError).length == 0) {
$(this).removeClass(classes.error);
}
});
}
else {
$(this).find(elements.controlGroupDiv).each(function () {
if ($(this).find(elements.inputValidationError).length > 0) {
$(this).addClass(classes.error);
}
});
}
},
onFormInputChange = function () {
/// <summary>Handles form input change event</summary>
var $controlGroup = $(this).parents(elements.controlGroupDiv);
// The delay leaves jquery validate some time to insert the validation error
setTimeout(function() {
if ($controlGroup.find(elements.inputValidationError).length == 0) {
$controlGroup.removeClass(classes.error);
} else {
$controlGroup.addClass(classes.error);
}
}, 500);
},
highlightInitialisedErrors = function () {
/// <summary>Highlight error inputs that have been initialised (e.g. part of initial page load)</summary>
$(this).find(elements.controlGroupDiv).each(function () {
if ($(this).find(elements.inputValidationError).length > 0) {
$(this).addClass(classes.error);
}
});
},
init = function () {
/// <summary>Initialises BootstrapValidate module to add support for Twitter Bootstrap to jQuery validate</summary>
$(function () {
$(elements.fieldValidationSpanAll).each(addInlineHelp);
$(elements.form).off('submit', onFormSubmit).on('submit', onFormSubmit);
$(elements.formInput).off('change', onFormInputChange).on('change', onFormInputChange);
$(elements.formInput).off('keyup', onFormInputChange).on('keyup', onFormInputChange);
$(elements.formInput).off('blur', onFormInputChange).on('blur', onFormInputChange);
$(elements.form).each(highlightInitialisedErrors);
});
};
return {
init: init
};
}(jQuery)).init();