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
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
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
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 );'>
You can use following Regex
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
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})$
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)" />