以下代码用来在用户输入时自动格式化电话号码,格式为『nnn-nnn-nnnn』,留在这里备忘。里面的正则表达式是 Google 到的,不得不佩服这个正则表达式的作者的功底。

1
2
3
4
5
6
7
8
9
10
11
12
$('body').on('keydown', 'input[type=tel]', null, function (e) {
var that = $(this);
var tel = that.val();

if (/^\d{4}$/.test(tel) || /^\d{3}-\d{4}$/.test(tel)) {
that.val(tel.replace(/(\d{3})(?!\-)/g, "$1-"));
}

if (tel.length > 12) {
that.val(tel.substr(0, 12));
}
});

留言

2014-07-29