我需要屏蔽 zip 字段,以便它允许经典的 5 位 zip (XXXXX) 或 5 + 4 格式 (XXXXX-XXXX)。
我可以这样做:
$('#myZipField').mask("?99999-9999");
但复杂的是,如果用户只输入 5 位数字,则不应该显示破折号。
这是迄今为止我想出的最好的方法 - 我可以将其扩展为在插入第 6 位数字时自动插入破折号,但这样做的问题是删除时的有趣行为(我可以阻止他们删除破折号,但它会修补补丁等等,这变成了一场噩梦):
$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});
是否有任何开箱即用的方法可以做到这一点,或者我必须自己推出?
I have a requirements for masking a zip field so that it allows the classic 5 digits zip (XXXXX) or 5 + 4 format (XXXXX-XXXX).
I could so something like:
$('#myZipField').mask("?99999-9999");
but the complication comes from the fact that dash should not be showing if the user puts in only 5 digits.
This is the best I came up with so far - I could extend it to auto-insert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion (I could stop them from deleting the dash but it would patching the patch and so forth, it becomes a nightmare):
$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});
Is there any out of the box way of doing this or do I have to roll my own?
发布评论
评论(5)
这个邮政编码实际上很简单,但是当您要处理更复杂的格式时,以下是使用插件解决它的方法(来自 演示页面):
This zip code is actually simple, but when you have a more complex format to handle, here is how it's solved with the plugin (from the demo page):
如果您已经在使用 jQuery,可能有数百个用于遮罩等的插件,例如:
http://www.meiocodigo.com/projects/meiomask/
所以我不认为你必须自己推出
If you're using jQuery already, there are probably hundreds of plugins for masks etc, for example:
http://www.meiocodigo.com/projects/meiomask/
So I don't think you'd have to roll your own
当您使用 jQuery Inputmask 插件并且想要使用 4 或 5 位数字值作为邮政编码时,您应该使用:
$('#myZipField').inputmask("9999[9]");
When you use jQuery Inputmask plugin and you want to use 4 or 5 digit values for zip code you should use:
$('#myZipField').inputmask("9999[9]");
为什么不让该字段透明,并在其后面放置一个文本对象,并将表单设置为浅灰色?因此,他们在背景中看到#######-####,然后对其进行配置,以便字母在键入时消失。此时,如果他们想输入额外的四个,就应该输入破折号,对吧?然后,如果脚本搞砸并输入 6 个数字,您可以操纵脚本自动插入连字符吗?
Why not have the field be transparent, and have a text object behind it with the form in light grey? So they see #######-#### in the background, and then rig it so the letters dissapear as they type. At that point, it suggests that they should enter a dash if they want to put the extra four, right? Then, you could just rig the script to autoinsert the hyphen if they mess up and type 6 numbers?
您不必使用不同的插件。只需移动问号,这样
您就应该使用:
而不是:毕竟,可选的不是整个字符串,而是
-
及以后的字符串。You don't have to use a different plug-in. Just move the question mark, so that instead of:
you should use:
After all, it isn't the entire string which is optional, just the
-
and onward.