2

How to validate following in Decimal value using Jquery?

I have created basic fiddle where i am able to validate number.

I am not allowing user to enter anything other then number, Dot(.) or Comma(,) (interchangeable), Backspace

HTML

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

JQUERY

$(document).ready(function () {
    $('.myTexbox').keypress(function (event) {
        return isDecimalNumber(event, this)
    });
});

function isDecimalNumber(eve, element) {
    var charCode = (eve.which) ? eve.which : event.keyCode
    if (
    (charCode != 8) //For Backspace Active
    &&
    (charCode != 44 || $(element).val().indexOf(',') != -1)
    //For comma
    &&
    (charCode != 46 || $(element).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))

    return false;
    return true;
}

Complete Fiddle: https://jsfiddle.net/s2t8fgn3/

Could you please help me in achieving that User can enter only two places after . or , like 123.02 only and Comma or Dot once inserted should not be repeated.

  • Required: Should work in IE 10 +

Update: Also we need to Copy paste into it. so how to manage that whether data is proper decimal and how to allow CTRL+V but not V.

fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • possible duplicate of http://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation – Kushal Aug 11 '15 at 12:17
  • Able to avoid duplication of , and . using (charCode != 44 || $(element).val().indexOf(',') != -1 || $(element).val().indexOf('.') != -1) and (charCode != 46 || $(element).val().indexOf('.') != -1 || $(element).val().indexOf(',') != -1) ....... But how to make it should upto two places and do not add more after two places. – fatherazrael Aug 11 '15 at 12:24

2 Answers2

3

I would add regexp check

$(element).val().toString().match("\\.[0-9]{2,}$")

see https://jsfiddle.net/2fpcg0ee/

update: different approach where you compare the value before and after

$(document).ready(function() {
    var oldVal = '';
    $('.myTexbox').keypress(function (event) {
        if (this.value.match("^[0-9]*[.,]?[0-9]{0,2}$"))
            oldVal = this.value;
    });
    $('.myTexbox').keyup(function (event) {
        if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
            $('.myTexbox').val(oldVal);   
        }
    });
});  

see https://jsfiddle.net/2fpcg0ee/4/

rhorvath
  • 3,525
  • 2
  • 23
  • 30
  • I have found a bug there, as soon as you match the regexp you can't change the field. I will try to fix it. – rhorvath Aug 11 '15 at 12:42
  • Can we keep comma and decimal both together in same above regular expression? as Dot and Comma is interchangeable in my case – fatherazrael Aug 11 '15 at 12:45
  • please take a look at update, old version is not really a good one, because you could have added '.' to any position in the text by chaning the cursor position and regexp would not catch that – rhorvath Aug 11 '15 at 13:15
  • Nops. Type fast and you will get all characters typed. – fatherazrael Aug 11 '15 at 13:22
  • could we validate the oldVal and in case its wrong just empty it? edited the fiddle – rhorvath Aug 11 '15 at 13:24
  • No Robin. Keep pressing keys and you will see value gets remove and other numbers comes in picture – fatherazrael Aug 11 '15 at 13:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/86701/discussion-between-fatherazrael-and-robin). – fatherazrael Aug 11 '15 at 13:29
  • since i don't see you in chat and cant be there anymore, this might be the combined version https://jsfiddle.net/jdxn1Lmn/5/ – rhorvath Aug 11 '15 at 15:19
  • Sorry time was over. I am implementing it just and test it in my solution. Thanks for kind help. :) – fatherazrael Aug 12 '15 at 06:26
  • I need to implement it on Paste and Drag-Drop too – fatherazrael Aug 14 '15 at 06:54
  • The last solution in the comments I provided you with (https://jsfiddle.net/jdxn1Lmn/5/) validates pasted values as well, it works. – rhorvath Aug 14 '15 at 07:16
  • I wrote a text and copy it using mouth and clicked in textbox and right click and pasted it and it gets pasted. Secondly i Dragged a value from mouse and dropped it here and it gets dropped – fatherazrael Aug 14 '15 at 07:50
  • yes, you are right. pasting with mouse does not trigger keyup event, i have added input listener to catch that, give it a try https://jsfiddle.net/jdxn1Lmn/12/ – rhorvath Aug 14 '15 at 08:11
0

I made some code, I hope it's that what you tried to achieve

function validateDecimal(num) {
    //goal: decimal number, only one [.,] allowed, only 2 digits after [.,]

    //first we check for invalid numbers
    var findInvalid = num.match(/[^0-9\,\.]/g);
    if(findInvalid) //found invalid chars
        return false;


    //now replace , to . (dot is more machinelike)
    var num = num.replace(/,/g,".");

    //now find number of occurences of .
    var count = (num.match(/\./g) || []).length;
    if(count > 1) 
        return false; //we have more than one . -> so its invalid

    //now we count the chars after the first .
    var indexOfDot = num.indexOf(".");
    if(indexOfDot == -1) 
        return true; //we have no dot - so its pure numeric (no decimal)
    var charsAfterDot = num.length - (indexOfDot+1);
    if(charsAfterDot > 2)
       return false; //we have more than 2 chars after dot - invalid

    return true; //every other case is valid
}

http://jsfiddle.net/7Ls7L3u9/ <<< to fiddle around

Kapsonfire
  • 1,013
  • 5
  • 17
  • Thank you. Created fiddle for same, i think i need to do more work around to get it work fully. https://jsfiddle.net/7Ls7L3u9/1/ – fatherazrael Aug 11 '15 at 12:57
  • the reason why your lookup doesnt work is, cause keypress fires before the new char is pushed in the textbox,.. – Kapsonfire Aug 11 '15 at 13:25