-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.simplemask.js
77 lines (63 loc) · 2.36 KB
/
jquery.simplemask.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
/**
* EXAMPLE USAGE
*
$(function() {
$('#test_input').simpleMask('aa-#9', {
allow_periods : true,
allow_commas : true,
allow_dashes : true
});
});
*/
$.fn.extend({
simpleMask : function(mask_string, custom_config) {
var config = $.extend({
allow_periods : true,
allow_commas : true,
allow_dashes : true
}, custom_config || {}),
mask_length = mask_string.length,
regex_map = {
'#' : /[a-z0-9\s]/i,
'a' : /[a-z]/i,
'9' : /[\d]/i
}
$(this).keydown(function(event) {
if(event.keyCode == 8) // ALLOW BACKSPACING
return true;
if(event.keyCode >= 37 && event.keyCode <= 40) // ALLOW ARROW KEYS
return true;
var mask_character = mask_string[$(this).val().length];
// Prevent characters that exceed the mask
if(typeof mask_character == 'undefined')
return false;
// Do we have a regex mapping for the current character in the mask string?
if(!regex_map[mask_character])
$(this).val($(this).val() + mask_character);
if($(this).val().length >= mask_length)
return false;
if(config.allow_commas && event.keyCode == 188) // ALLOW COMMA
return true;
if(config.allow_dashes && event.keyCode == 189) // ALLOW DASHES
return true;
if(config.allow_periods && event.keyCode == 190) // ALLOW PERIOD
return true;
if(regex_map[mask_character] && String.fromCharCode(event.keyCode).match(regex_map[mask_character]))
return true;
// Any other character returns false
return false;
}).keyup(function() {
var processed_string = '',
inbound_value = $(this).val();
for(var i in inbound_value) {
if(regex_map[mask_string[i]]) {
if(inbound_value[i].match(regex_map[mask_string[i]]))
processed_string += inbound_value[i];
} else {
processed_string += mask_string[i];
}
}
$(this).val(processed_string);
});
}
});