/
knockout-validation.js
41 lines (38 loc) · 1.25 KB
/
knockout-validation.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
import $ from 'jquery';
import ko from 'knockout';
import 'jquery-validation';
/**
* Binds a form element to use jQuery validation tools
* The argument should be a an object of settings from jQuery Validate.
*
* jQuery Validation Docs:
* https://jqueryvalidation.org/validate/
*
* Usage Example
* -------------
* <form class="form-horizontal" data-bind="validate: validationSettings">
* <!-- Inputs in a validated form must have a name. -->
* <input name="name" value="" type="text" />
* <!-- Either buttons or input[type=submit] works fine.. -->
* <input type="submit" value="Add" />
* </form>
*
*/
ko.bindingHandlers.validate = {
init: (element, valueAccessor) => {
const value = valueAccessor();
// Add a new handler callback that adds the form as a param for
// checking overall validity.
// Preserve the old onfocusout in case it was being used.
value.ogonfocusout = value.onfocusout;
value.onfocusout = (input, event) => {
if (value.updateHandler) {
value.updateHandler($(element), input);
}
if (value.ogonfocusout) {
value.ogonfocusout(input, event);
}
};
$(element).validate(ko.unwrap(value));
}
};