Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Regular Expression for Currency

    Hi - Below Code works absolutely fine for currency in all formats with one expception that is I want to allow only one single 'dot'. But it takes second one in ffew cases like

    When you enter something like 1234.56 and then come back enter dot(.) between 56.It will take and focus out it will turned it into 0.00 . So How I restrict this by allowing single dot(.) through the below reglar expression.

    Don't want to mess this logic much?


    *******************
    $(".currency").bind('keypress',function(event) {

    if (event.keyCode == 9)
    return true;
    var regex = new RegExp("^[0-9.\.{1},\b]+$");
    var key = String
    .fromCharCode(!event.charCode ? event.which
    : event.charCode);
    if (!regex.test(key)) {
    event.preventDefault();
    return false;
    }

    var val = $(this).val();
    var tempArray = new Array();
    var tempArray = val.split(".");
    if (tempArray.length > 2) {
    event.preventDefault();
    return false;
    }

    });

    $(".currency").bind('keyup',function(event) {

    if (event.keyCode == 9)
    return true;

    var regex = new RegExp("^[0-9.\.{1},\b]+$");

    var val = $(this).val();
    var tempArray = new Array();
    var tempArray = val.split(".");

    if (tempArray.length > 2) {
    $(this).val(
    val.substring(0,
    val.length - 1));
    event.preventDefault();
    return false;
    }

    if (tempArray.length == 2) {
    var afterDecimals = tempArray[1];
    if (afterDecimals.length > 2) {
    $(this)
    .val(
    tempArray[0]
    + '.'
    + afterDecimals
    .substring(
    0,
    2));
    }
    }

    });



    $(".currency").blur(function() {

    if ($(this).val() != '') {
    $(this).val(
    formatCurrency($(this)
    .val()));
    }
    });

    $(".currency").keyup(function(event) {

    if (event.keyCode == 13) {

    if ($(this).val() != '') {
    $(this).val(
    formatCurrency($(this)
    .val()));
    }

    }
    });

    function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
    cents = "0" + cents;
    for ( var i = 0; i < Math
    .floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3))
    + ','
    + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
    }

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Seems a long-winded approach.

    Have a look at this:-

    Code:
    <input type = "text" id = "txt1" size = 8" onchange ="oneOnly(this)">
    
    <script type = "text/javascript">
    
    function oneOnly(which) {
    
    var reqChar = "." // decimal point
    var must = true;  // if character is required, false if optional
    var x = which.value;
    x = x.replace(/^\s+|\s+$/,"");   // strip leading and trailing spaces
    
    if (x == "") {   // field is mandatory
    alert ("This field is mandatory.  You must enter a number.");
    which.focus();
    return false;
    } 
    
    if(/[^0-9\.]/g.test(x)) {  // not - so no negative numbers allowed
    alert ("Only positive numbers are allowed in this field");
    which.value = "";
    which.focus();
    return false;
    }
    
    if (x > 100) {  // or whatever maximum value may apply
    alert ("Maximum value is 100.  Please re-enter.");
    which.value = "";
    which.focus();
    return false;
    }
    
    var atPos = x.indexOf(reqChar);  
    if (must && atPos == -1) {
    alert ("Your number must contain a decimal point.  Please edit your entry.");
    which.focus();
    return false;
    }
    
    if (x.indexOf(reqChar, atPos + 1) > - 1) {
    alert ("Only one decimal point allowed!  Please edit your entry.");
    which.focus();
    return false;
    }
    
    x = Number(x);
    x = x.toFixed(2);  // make 2 decimal places
    x = Number(x);
    which.value = x;  // write back to the field
    
    alert ("Entry is valid");  // delete after testing
    
    }
    
    </script>

    Rather than alerts which are obsolete you should use DOM methods to display a message to your user.


    To format numbers with commas and $ sign:-

    Code:
    function formatNumber(x) {
    return x.toFixed(2).split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
    }
    
    var num = formatNumber(1234567.8897);
    num = "$" + num;
    alert (num);

    Quizmaster: Name a country with a Pacific coastline.
    Contestant: Egypt
    Last edited by Philip M; 03-25-2014 at 09:13 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    New to the CF scene
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks Philip!!

    I'm learning. But business doesn't want to change any existing logic but need a fix to block(don't allow) second dot(.) like the way the above logic blocking alaphabets.

    And mostly they want to avoid showing errors for the user and try to format as maximum as it can.

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Try changing your regex to

    Code:
    var x = "a123.345";  // a string currency value entered by the user with unwanted characters
    x = x.replace(/([^0-9\.])/gi,"");  // strip unwanted characters
    x = Number(x).toFixed(2);  // make a string with 2DP
    // alert (x);  // for testing
    if (!/^\d+\.\d{2}$/.test(x)) {     // one or more digits, decimal point, two digits, nothing but
    // alert ("Invalid");
    }
    Last edited by Philip M; 03-25-2014 at 06:42 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    New to the CF scene
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Try changing your regex to

    Code:
    var x = "a123.345";  // a string currency value entered by the user with unwanted characters
    x = x.replace(/([^0-9\.])/gi,"");  // strip unwanted characters
    x = Number(x).toFixed(2);  // make a string with 2DP
    // alert (x);  // for testing
    if (!/^\d+\.\d{2}$/.test(x)) {     // one or more digits, decimal point, two digits, nothing but
    // alert ("Invalid");
    }
    Thanks Philip!! Your logic helped me think other way.

    And I fixed it by adding the below logic in KeyPress

    if (key == "." && tempArray.length == 2){
    event.preventDefault();
    return false;
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •