用于格式化输入的 jQuery 插件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/992126/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:21:11  来源:igfitidea点击:

jQuery plugin for formatting inputs

jquerymaskedinput

提问by antony.trupe

I want to accept values in any of the following format:

我想接受以下任何格式的值:

  • -$5
  • -$5.00
  • $5
  • $5.00
  • -$5
  • - $5.00
  • 5 美元
  • 5.00 美元

Is it possible to do that using Masked Input Plugin?

是否可以使用Masked Input Plugin做到这一点?

If not, what plug-in am I looking for?

如果没有,我在寻找什么插件?

How do I indicate a character is optional?

我如何表示一个字符是可选的?

The code I've got so far

到目前为止我得到的代码

$.mask.definitions['~']='[ +-]';
$(".currency").mask("~");

采纳答案by glmxndr

Here is how i would implement the validation rule :

这是我将如何实现验证规则:

$('.myinput').val().match(/^[+-]?$\d(?:\.\d\d)?$/)

The problem with your pattern is that it is not fixed-length, so hard to code in mask, and you may encounter some people giving $3.5, which is not what you want. With such a pattern of yours, I think it will be hard not to fall back on regexp matching.

你的模式的问题是它不是固定长度的,所以在掩码中很难编码,你可能会遇到一些人给3.5美元,这不是你想要的。有了你的这种模式,我认为很难不依赖正则表达式匹配。

You may consider making the cent part mandatory, in which case your pattern is almost ok, just add .99 at the end and it should do it (although as a user I would hate to have to start my currency with a space character...).

您可以考虑强制使用美分部分,在这种情况下,您的模式几乎没问题,只需在最后添加 0.99 就可以了(尽管作为用户,我不希望以空格字符开头我的货币.. .)

回答by Diego Plentz

Just to clarify Antony response, the plugin that he's using is jquery-maskmoney:

为了澄清安东尼的回应,他使用的插件是 jquery-maskmoney:

https://github.com/plentz/jquery-maskmoney

https://github.com/plentz/jquery-maskmoney

回答by sherif sakr

I think this will help you.

我认为这会对你有所帮助。

Use the syntax

使用语法

$(mask_id).maskMoney({showSymbol:false,decimal:'.',precision:2});

You can show the symbol but it is probably better to hide it.

您可以显示符号,但最好隐藏它。

回答by Jake

I know that in mask you can also make some of the mask optional, so you might be able to get away with this

我知道在面具中你也可以选择一些面具,所以你可以摆脱这个

$.mask.definitions['~']='[ +-]';
$(".currency").mask("~?.99");

回答by baku

$.mask.definitions['~']='[ +-]';

$(".currency").mask("~$9?.99");

$(".currency").mask("~$9?.99");

is it not work???

不行吗???