调用方式

$(“#cdkey”).formatCdkey({});

默认参数

{
separator:”-“, //默认分隔符
splitLength:4, //分割长度
groupCount:5, //分隔符分隔的组数
isSetCase:true, //是否转换大小写
isToUpCase:true //true转换大写;false转换小写(isSetCase:true时生效)
}

ps:separator仅支持单字符;

默认格式样例:F15A-D165-F168-94BF-A4T9

查看Demo

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
(function ($) {
function containSpecial(s) {
var containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);
return (containSpecial.test(s));
};
$.fn.formatCdkey = function (options) {
if (options.separator && options.separator.length > 1) {
console.log("unsupport separator!");
return;
};
var defaults = {
separator : "-", //默认分隔符
splitLength : 4, //分割长度
groupCount : 5, //分隔符分隔的组数
isSetCase : true, //是否转换大小写
isToUpCase : true //转换大写
};
var opts = $.extend({}, defaults, options);
var $this = $(this);
var timeoutFlag;
var maxLength = opts.splitLength * opts.groupCount + opts.groupCount - 1;
$this.keyup(function (e) {
clearTimeout(timeoutFlag);
if (opts.isSetCase) {
$this.val(opts.isToUpCase ? $this.val().toUpperCase() : $this.val().toLowerCase());
}
var fixVal = function () {
var regPrefix = "";
if (containSpecial(opts.separator)) {
regPrefix = "\\";
};
var aval = $this.val().replace(new RegExp(regPrefix + opts.separator, "g"), "");
if (aval.length >= opts.splitLength) {
var avalArray = aval.split("");
var newVal = "";
for (var i = 0; i < avalArray.length; i++) {
if (i > 0 && (i + 1) % opts.splitLength == 0 && newVal.length <= maxLength) {
newVal += (avalArray[i] + opts.separator);
} else {
newVal += avalArray[i];
}
}
//截取最大长度约束的字符长度
$this.val(newVal.substring(0, Math.min(newVal.length, maxLength)));
};
};
if (e.keyCode == 8) { //删除键
timeoutFlag = setTimeout(function (){
fixVal();
}, 2000);
return;
};
fixVal();
});
}
})(jQuery);
$(document).ready(function () {
$("#cdkey").formatCdkey({});
});