-1

i Want to validate a text field in keyup event .

in the field it should accept money type decimal like

(12.23) (.23) (0.26) (5.09) (6.00)

if i enter some wrong value then it should return to the previous value and remove the wrong one

abiansh
  • 79
  • 2
  • 2
  • 9
  • Thats your requirement, what have you tried so far? I would be easy for us to point out the mistake if you show us the code. – Praveen Aug 28 '13 at 06:20
  • @abiansh what does it mean when you say "it should return to the previous value" – zzlalani Aug 28 '13 at 06:33
  • var theEvent = evt || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); var regex = /^(\d{0,2})(\.\d{2})$/; // number with 2 decimal places if (!regex.test(key)) { theEvent.returnValue = false; //--- this prevents the character from being displayed if (theEvent.preventDefault) theEvent.preventDefault(); } – abiansh Aug 29 '13 at 05:08

4 Answers4

4

I think something like this might be your best bet

var isValidCurrency = function(str) {
  var num = parseFloat(str);
  return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};

Some tests

isValidCurrency("1234.56");   // true
isValidCurrency("1234.565");  // false
isValidCurrency("1234");      // false
isValidCurrency("foo");       // false
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

Try this:

function evMoneyFormat(evt) {
    //--- only accepts accepts number and 2 decimal place value
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        //--- this prevents the character from being displayed
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}

The control:

<input type='text' onkeyup='evMoneyFormat( e );'>
Arturs
  • 1,258
  • 5
  • 21
  • 28
0

You can use following Regex

val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
    alert("wrong");
} else {
    alert("right");
}

http://jsfiddle.net/rtL3J/1/

EDIT

Please note that if the numbers preceding dot (.) has limit of length to two then the code valid code is

^(\d{0,2})(\.\d{2})$

else if there is no limit then just remove the 2 from the code i.e.

^(\d{0,})(\.\d{2})$
zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

Try following code

function validateDecimal(num){

   var dotPosition=num.indexOf(".");

   if(dotPosition=="-1"){
      document.getElementById('cost').value= num+".00"
   }
}

And in html

<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />
Rejayi CS
  • 1,034
  • 1
  • 10
  • 22