Reputation: 31
I have a textbox in column "amount". Here I want to enter only 5 numbers before decimal and 2 numbers after decimal like this "99999.99". I want to do this in jquery. I am using the following code,
editor: { type:"textbox",style:'z-index:10000;position:relative;',init:filterhandler,cls:'com1',},
var filterhandler = function (ui) {
$('.com1').keyup(function(){
var value = $(".com1").val();
if(value.indexOf('.') === -1){
var max=99999;
if( value > max){
$('div.jGrowl').find('div.jGrowl-notification').parent().remove();
$.jGrowl("You can't enter more than 99999.99", { sticky: false });
value = value.substring(0,5);
$(".com1").val(value);
value = value.substring(0,3);
}
}else{
var max = 2;
var v=value.split(".");
var fstvalue= v[0];
var scndValue=v[1];
$('.com1').css({ "border-color": "rgb(153, 188, 232)"});
if(scndValue.length > max){
$('div.jGrowl').find('div.jGrowl-notification').parent().remove();
$.jGrowl("You can't enter more than 99999.99", { sticky: false });
scndValue = scndValue.substring(0,2);
value=fstvalue+"."+scndValue;
$(".com1").val(value);
}
}
});
};
Please help me, In this code how to restrict the value.
Upvotes: 0
Views: 595
Reputation: 31
The easiest way is add, "input.js" file first. And then use the following 2 lines. Its working perfectly.
var inputConfig = {aSep:'', aNeg:'', mDec:2, mNum:5};
$('.com1').autoNumeric(inputConfig);
Upvotes: 0
Reputation: 4207
you can use regular expression instead!
function validateAmount(amount){
var re = /^\d{1,5}(\.\d{1,2})?$/;
return re.test(amount);
}
Usage:
if(validateAmount(20.2)) console.log('validated');
else console.log('validation failed');
Explination:
\d //for digits
{1,5} // min 1 char to max 5 chars
\. // to escape char .
\d //again digits
{0,2} again min 0 to max 2 chars
? //for optional, as after decimal points are optional, it's needed to be be wrapped in parentheses.
Upvotes: 0
Reputation: 2927
Use Regex to test if the input matches your input range. Fiddle
([1-9]{1,5})
limits the first 5 characters to only numbers and cannot start with a 0.
(\.([0-9]{2})?
limits the user to only 2 places after the .
and is also a lazy selector meaning this doesn't have to apply. Example: 123 will match while 123.23 matches as well.
$('input').blur(function() {
var pat = /([1-9]{1,5})(\.([0-9]){2})?/g;
if ( pat.test(this.value) ) {
console.log("You're Good!");
} else {
console.log('No match!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Upvotes: 2
Reputation: 2523
Could you just use math like so?
$('form').submit(function(e) {
e.preventDefault();
amount = $('.amount').val();
if(amount > 9999.99) {
alert('you cannot enter more than 9999.99');
} else {
alert('all good here');
}
});
http://jsbin.com/tugimayiro/1/
Upvotes: -1