jQuery plugin for formatting inputs

21,826

Solution 1

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.

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...).

Solution 2

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

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

Solution 3

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.

Solution 4

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("~$9?.99");

Solution 5

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

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

is it not work???

Share:
21,826
antony.trupe
Author by

antony.trupe

husband, father, developer, tester, maker, business process analyst, usa citizen, human

Updated on July 09, 2022

Comments

  • antony.trupe
    antony.trupe almost 2 years

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

    • -$5
    • -$5.00
    • $5
    • $5.00

    Is it possible to do that using 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("~$9");