jQuery 输入掩码长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2479653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery input mask length
提问by Tim
I have an input field and I want to limit it to alphanumerical (A-Z, a-z, 0-9) characters only, with a MINIMUM field length of 5, and a maximum length of up to 15 characters total.
我有一个输入字段,我想将其限制为字母数字(AZ、az、0-9)字符,最小字段长度为 5,最大长度总共为 15 个字符。
Does anyone know how I can do this using jQuery?
有谁知道我如何使用 jQuery 做到这一点?
I'm trying to use the jQuery input mask by digitalBush - http://digitalbush.com/projects/masked-input-plugin/
我正在尝试使用 digitalBush 的 jQuery 输入掩码 - http://digitalbush.com/projects/masked-input-plugin/
The problem is that UNLESS I enter 15 characters, the field goes blank. If I enter "012345678912345" (15 characters) in the input field then the value is stored and it's fine.
问题是,除非我输入 15 个字符,否则该字段变为空白。如果我在输入字段中输入“012345678912345”(15 个字符),则该值将被存储,这很好。
But if I enter "12345" as a username, when that input box loses focus its value goes back to being blank. Is there something that I can change in the "definitions" or options somewhere that fixes this?
但是如果我输入“12345”作为用户名,当该输入框失去焦点时,它的值会变回空白。有什么我可以在“定义”或选项中改变的东西来解决这个问题吗?
Many thanks for your help :)
非常感谢您的帮助 :)
Tim
蒂姆
回答by Dustin Laine
This is done like this: The '*' is alphanumeric, anything after the '?' is optional.
这是这样完成的:'*' 是字母数字,'?' 之后的任何内容。是可选的。
jQuery(function($){
$("#elem").mask("*****?**********");
});
回答by Bogdan Trusca
Also If you want to change the mask depending on character length, as I did. Found this great way:
另外,如果您想根据字符长度更改掩码,就像我一样。找到了这个好方法:
var arr = ['HomePhone',
'CellPhone',
'EmergencyPhone'
];
for (var i in arr)
{
$('input[name='+arr[i]+']').mask("999-999-9999?9")
.keydown(function () {
var $elem = $(this);
var a = this.value.replace(/\D/g, "").length;
setTimeout(function () {
var n = $elem.val().replace(/\D/g, "").length;
if (n !== a && (n === 10 || n === 11)) {
var mask = (n === 11 ? "9999-999-9999" : "999-999-9999?9");
$elem.mask(mask);
}
}, 1);
});
}