Decimal Validation In The Textfield Using Javascript Or Jquery
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 shoul
Solution 1:
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
Solution 2:
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})$
Solution 3:
Try this:
functionevMoneyFormat(evt) {
//--- only accepts accepts number and 2 decimal place valuevar 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 placesif (!regex.test(key)) {
theEvent.returnValue = false;
//--- this prevents the character from being displayedif (theEvent.preventDefault) theEvent.preventDefault();
}
}
The control:
<inputtype='text' onkeyup='evMoneyFormat( e );'>
Solution 4:
Try following code
functionvalidateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
And in html
<inputtype="text"id='cost' onkeyup="validateDecimal(this.value)" />
Post a Comment for "Decimal Validation In The Textfield Using Javascript Or Jquery"