Input mask for numeric and decimal
Asked Answered
G

8

20

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.

Garofalo answered 16/8, 2013 at 9:9 Comment(12)
Ehm... if the database field is numeric(6,2) then the number of decimals can't be "2 or 3 according to choice of the user". What am I missing?Peavey
yes i changed it in database(6,3), the decimal two or three is only optional in the display.Garofalo
but the probleme is the sameGarofalo
I am trying to work with regex, but the regular expression is wrong, I get an error. var ex=/[0-9]{1-3}\.[0-9]{2} I want to put two 0 not when I enter the decimal value.please helpGarofalo
Always do your validation on server side and client-side (javascript) only for usability, but don't rely on it. Now, if I understand you correctly, you want to be able to enter 0 o 999 with or without 2 or 3 decimals? Since I'm not sure of the meaning of mantissa, as what I google doesn't really match what you're describing. About the last comment, entering "00" passes the validation and you want it to not pass, is that correct?Gaseous
mantisse is the decimal part for example: 2.657, the matisse is 0.657Garofalo
So what exactly is your problem with the regex? I don't understand what you want to say with the "I want to put two 0 not when I enter the decimal value". I thought it referred to the part before the decimal period, in your example 2 where entering 00 passed validation which I addressed in my answer, however now I'm thinking it's something else, but I'm not sure what. Could you clarify? Possibly review my answer and say what I misinterpreted in your question?Gaseous
I want to force my html input the following display: 14 digital maximun(from 1 to 14) and the Effective Three decimal point, if the user does not specify the value of the points after they take the default 000 Example: Enter 5 show 5.000 enter 5.2 Show 5.200 enter 22222 show 22222.000 display. please helpGarofalo
Ahhh, now I understand. I will revise my answer with a solution suited to your needs. I just have one more question - would you rather go for a solution where the textbox has 0.00 (or 0.000 depending on preference) and then let the user only make allowed changes (i.e. not add or delete, only change the part after the decimal point and change the part before the decimal point be changed to any number between 0 and whatever the max is or does the user have to have a blank box by default? Also, is the 14 max digits including the part after the decimal or does the part after decimal not count?Gaseous
14 digital max before the point and three after the point.Garofalo
I need just to force digital numbers before the point to 14 number maxmimum like that: the user can enter vallues from 0.000 to 99999999999999.999Garofalo
I edited my answer to what I now believe are your requirements.Gaseous
P
22

You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:

HTML

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

JQuery

$(".numeric").numeric({ decimal : ".",  negative : false, scale: 3 });

This is the whole source.
And I've prepared this fiddle so you can see how it works.

Povertystricken answered 16/8, 2013 at 13:40 Comment(7)
I tried this jsfiddle.net/lun471k/4CHfC/but the regular expression here :/(\d{1,14})(\.\d{1,3}){0,1}$/(regex) is false. I need your helpGarofalo
I need just to force digital numbers before the point to 14 number maxmimum like that: 0.000 to 99999999999999.999Garofalo
when I use precision 4, i can enter till 9999, what I want to have with precision 4 is 99.99Garofalo
@najeh22: customize the plugin.Povertystricken
at first I worked with the changed plugin that's why it doesn't work althought i add precision, but now, I return to your js fiddle and I just modify precision and it's fine thanks.Garofalo
Unfortunately jquery.numeric is not applicable. In recent browsers generates a large amount of Errors.Terramycin
What is "scale" for?Shien
R
12

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

Relucent answered 10/12, 2015 at 23:29 Comment(3)
I've tried this mask in desktop and mobile devices. It doesn't work for me.Phraseology
Let me update: This is the best and simplest mask. It was not working for me because in Brazilian Portuguese we use "," and not ".". So we write 1.000.000,00 and not 1,000,000.00 like in English. So, if your system is in Portuguese use this: $(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"}); And do not forget to add the imports.Phraseology
This saved my life.Esophagus
S
10

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

Sighted answered 16/8, 2017 at 15:23 Comment(2)
It doesn't work too. The input shows "1.5" but the app gets "15"Phraseology
It works for me. If you want to disable the rightAlign, you can do 'rightAlign': false, This is the answer I've been looking for for quite a while! Thanks a lot!Arlenearles
A
4

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');
});
Abdication answered 8/12, 2018 at 7:23 Comment(1)
It doesn't work too. The input shows "1.5" but the app gets "15".Phraseology
C
2

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
    }
}
Cummerbund answered 8/4, 2018 at 12:35 Comment(0)
G
0

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.

Gaseous answered 16/8, 2013 at 15:18 Comment(5)
/^[0-9]{1,14}\.[0-9]{2}$/ is not correct, there is something wrong cause i can enter here numbers as much as I want, letters tooGarofalo
I use this but ex is not correct function checkDec(el){ var ex=/^[0-9]{1,3}\.[0-9]{2}$/; if(ex.test(el.value)==false){ el.value = el.value.substring(0,el.value.length - 1); } }Garofalo
@Garofalo You can enter whatever you want, but while the text that is entered is invalid, the background will turn red, that's what I mean by not enforcing the mask. You have to do validation server-side anyway so that regex should be good for server side validation AND for pre-submit if you need it. However, if you want a realtime mask that doesn't let you input an invalid value, I would go with LeftyX's solution since this is much more complicated to achieve (for instance, you have to let the user enter 2., but that is not a valid value, hence the problems.Gaseous
yes you are right and that's what I said, with checkDec(el) my function there is something wrong with the regex expression.Garofalo
I'm having trouble understanding you. Can you create a JSFiddle with what you have so far and then explain how to see the problem in that JSFiddle? I hope that would clear the confusion and I (or someone else) would be able to understand what exactly is bugging you.Gaseous
M
0

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

Misleading answered 6/5, 2018 at 8:28 Comment(0)
P
0

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.

Phraseology answered 12/6, 2019 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.