forked from hanford/angular-date-input
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (97 loc) · 2.63 KB
/
index.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
var StringMask = require('string-mask')
module.exports = require('angular')
.module('angular-date-input', [])
.directive('dateInput', dateDirective)
.name
function dateDirective () {
return {
restrict: 'EA',
require: 'ngModel',
link: link
}
}
function link (scope, element, attrs, ctrl) {
var SEPARATOR = '/'
var MM_DD_YYYY = /^\D*(\d{1,4})(\D+)?(\d{1,2})?(\D+)?(\d{1,4})?/
var dateMask = new StringMask('00/00/0000')
function removeNonDigits (value) {
return value.replace(/([A-Z]|[a-z])/g, '')
}
function applyDateMask (value) {
var formatedValue
formatedValue = dateMask.apply(value) || ''
return removeNonDigits(formatedValue.trim())
}
function formatter (value) {
if (ctrl.$isEmpty(value)) {
return value
}
return value || ''
}
var parseDate = function (value) {
var parts = value.match(MM_DD_YYYY)
if (!parts) return []
var month = parts[1] || ''
var separator1 = parts[2] || ''
var date = parts [3] || ''
var separator2 = parts[4] || ''
var year = parts[5] || ''
if (year.length > 0) {
separator2 = SEPARATOR
} else if (separator1 === ' /') {
month = month.substring(0, 1)
separator1 = ''
} else if (month.length === 2 || separator1) {
separator1 = SEPARATOR
} else if (month.length > 2) {
month = month.substring(0, 2)
separator1 = ''
} else if (month.length === 1 && month !== '0' && month !== '1') {
month = '0' + month
separator1 = '/'
} else if (date.length === 1 && date !== '0' && date !== '1' && date !== '2' && date !== '3') {
date = '0' + date
separator2 = '/'
}
if (date && parseInt(date, 10) > 31) {
date = 31
}
if (month && parseInt(month, 10) > 12) {
month = 12
}
var currentYear = (new Date()).getFullYear()
if (year && parseInt(year, 10) > currentYear) {
year = currentYear
}
return [
month,
separator1,
date,
separator2,
year
].filter(Boolean)
}
var parser = function (value) {
if (ctrl.$isEmpty(value)) {
return value
}
var newValue = removeNonDigits(parseDate(value).join(''))
var formattedValue = formatter(newValue)
if (ctrl.$viewValue !== newValue) {
ctrl.$setViewValue(newValue)
ctrl.$render()
}
return removeNonDigits(newValue)
}
element.on('keydown', function (ev) {
if (ev.keyCode === 8) {
var parts = parseDate(ev.target.value)
if (parts.length === 2) {
ctrl.$setViewValue('')
ctrl.$render()
}
}
})
ctrl.$formatters.push(formatter)
ctrl.$parsers.push(parser)
}