-1

Ultimately I want a mask that only allows an integer to be entered, or if a decimal/period is entered: allow 0 - 2 digits after the decimal point.

Valid Input

1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11

Invalid Input

a
a.
1.a
1.111
1.1111
  • string allows any number of digit characters, but only allows 1 decimal/period
    • if a period/decimal exists: only allow 2 digit characters after the decimal

This regular expression does just that:

^\d*\.?([\d]){0,2}$

Now I need to apply this as a mask to an input. I am using Robin Herbots' Inputmask. I am really struggling making this work.

I am aware that there is the alias currency, but that does not work exactly as desired. What I want is for the input to default to blank on focus/unfocus unless there is input. currency defaults to 0.00. I also want to allow the user to delete everything from the field so it will be blank. currency does not allow you to leave the input blank. Instead it will only allow you to leave the field 0.00.

$('.moneyfield').inputmask("999", {rightAlign: true, numericInput: true});

The specific mask should go in the "999" spot. I could not figure out how to use the built in masks, so that was why I attempted to plug a regular expression into the mask. So far I have been unsuccessful with both strategies.

Another attempt was to use the currency alias and then just override it to what I want it to do. I wasn't successful with that either. Here is the definition of the currency mask:

    currency: {
        prefix: "$ ",
        groupSeparator: ",",
        alias: "numeric",
        placeholder: "0",
        autoGroup: !0,
        digits: 2,
        digitsOptional: !1,
        clearMaskOnLostFocus: !1
    }
Neil
  • 4,578
  • 14
  • 70
  • 155
  • a down vote with no explanation? – Neil Nov 04 '16 at 15:59
  • You can easily use the `pattern` attribute of inputs in HTML5. It allows you to mask input elements with regular expression exactly like you want. Check out the [documentation](http://www.w3schools.com/TAGS/att_input_pattern.asp) – Vivek Pradhan Nov 04 '16 at 16:04
  • @VivekPradhan great suggestion, unfortunately I need it to work with Safari, and this feature isn't supported in Safari. – Neil Nov 04 '16 at 16:17

1 Answers1

1

I figured it out. You just need to override a couple fields within the currency alias:

$('.money_field').inputmask({alias: 'currency', rightAlign: true, placeholder: "", prefix: '', autoGroup: false, digitsOptional: true});
Neil
  • 4,578
  • 14
  • 70
  • 155