[javascript] Input mask for numeric and decimal

I realized a software application management invoicing after having tested my program I noticed the following error: my table in sqlserver contains: price numeric (6,2) the user of my program enter price as 555.00 is good. but when he put 555555 it's error, so I need to specify the mask where the mantissa is optional 0 to 999 and the decimal part is programmable 2 or 3 according to choice of the user, I'm using JQuery Masked input plugin and I have not found good regular expression, please, help, I'm working with jsp / servlet.

This question is related to javascript jquery html regex input-mask

The answer is


or also

<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€  $" size=25>

with

function handleNumber(event, mask) {
    /* numeric mask with pre, post, minus sign, dots and comma as decimal separator
        {}: positive integer
        {10}: positive integer max 10 digit
        {,3}: positive float max 3 decimal
        {10,3}: positive float max 7 digit and 3 decimal
        {null,null}: positive integer
        {10,null}: positive integer max 10 digit
        {null,3}: positive float max 3 decimal
        {-}: positive or negative integer
        {-10}: positive or negative integer max 10 digit
        {-,3}: positive or negative float max 3 decimal
        {-10,3}: positive or negative float max 7 digit and 3 decimal
    */
    with (event) {
        stopPropagation()
        preventDefault()
        if (!charCode) return
        var c = String.fromCharCode(charCode)
        if (c.match(/[^-\d,]/)) return
        with (target) {
            var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
            var pos = selectionStart + 1
        }
    }
    var dot = count(txt, /\./, pos)
    txt = txt.replace(/[^-\d,]/g,'')

    var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
    var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
    if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return

    txt = txt.split(',')
    if (integers && txt[0] && count(txt[0],/\d/) > integers) return
    if (decimals && txt[1] && txt[1].length > decimals) return
    txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')

    with (event.target) {
        value = mask[1] + txt.join(',') + mask[5]
        selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot) 
    }

    function count(str, c, e) {
        e = e || str.length
        for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
        return n
    }
}

If your system is in English, use @Rick answer:

If your system is in Brazilian Portuguese, use this:

Import:

<script
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script     src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>

HTML:

<input class="mask" type="text" />

JS:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});

Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.

It is it, I hope that it help someone. I spend a lot of time to understand it.


Use tow function to solve it ,Very simple and useful:

HTML:

<input class="int-number" type="text" />
<input class="decimal-number" type="text" />

JQuery:

//Integer Number
$(document).on("input", ".int-number", function (e) {
  this.value = this.value.replace(/[^0-9]/g, '');
});

//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.


using jQuery input mask plugin (6 whole and 2 decimal places):

HTML:

<input class="mask" type="text" />

jQuery:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});

I hope this helps someone


You can do it using jquery inputmask plugin.

HTML:

<input id="price" type="text">

Javascript:

$('#price').inputmask({
  alias: 'numeric', 
  allowMinus: false,  
  digits: 2, 
  max: 999.99
});

https://codepen.io/vladimir-vovk/pen/BgNLgv


Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready

$(document).ready(function() {
    $('selectorForTextbox').bind('keyup', function(e) {
        if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
            $(this).addClass('invalid');
        } else {
            $(this).removeClass('invalid');
        }
    });
});

Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.

The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to input-mask

Input mask for numeric and decimal