Javascript currency validation doesn't work if clamp button - javascript

I want to validate my input according following requirements:
value can be from 1.00 to 9999.99
value fractional part cannot have more than 2 digits
I have wrote following code:
html:
<input id="amount" maxlength="7" type="text" />
js:
$("#amount").on("keyup", function(){
var valid = /^[1-9]{1}\d{0,3}(\,\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
But if I clamps '0' it works bad.
Please help to fix.
JSFIDDLE
P.S.
If I press '0' for 3-4 seconds I see
expected result - all input input be clear

$("#amount").on("input", function(){
var valid = /^[1-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
http://jsfiddle.net/a2eqrquf/
My Regex isn't really on point, so someone might be able to tidy that up a bit more than I can. But that is working as it should.

This is what the number input was made for just use the following HTML:
<input id="money-input" type="number" value="1" min="1" max="9999.99" step="0.01">
If your want to restrict the number of decimals that can be entered you could simply add some JavaScript to round of the number:
(function() {
var input = document.getElementById('money-input');
input.addEventListener('blur', function() {
this.value = Math.round(this.value * 100) / 100;
});
})();

I have updated your regular expresion, so now it's working like you want.
Demo: http://jsfiddle.net/vY39r/391/
$("#amount").on("input", function(){
var valid = /^[0-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
hope it's helps.

$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var text = $(this).val();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
});
$(".allownumericwithdecimal").live("blur",function (event){
var text = $(this).val();
if((text.indexOf('.') != -1)){
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2){
text = text.toString(); //If it's not already a String
text = text.slice(0, (text.indexOf("."))+3); //With 3 exposing the hundredths place
$(this).val(text);
}
}
});
this is what i use personally

Related

How to PREVENT (Not Validate) Users from entering more than 4 Decimals in an HTML Field [duplicate]

I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});

decimal places auto format in price jquery

i am trying to covert decimal places on type input field like
Number starts from 0.00
so at first place it will be 0.00 in input field
than i type 1 than it should become 0.01
than i type 2 than it should become 0.12
than 0 so it should become 1.20 and lastly
when i type 0 than it should become 12.00
0.01, 0.12, 1.20, 12.00.
I tried some methods which already given in SO but not successful.
Please suggest me another methods if possible. thank you.
i tried like this
$(document).on('keyup','.price',function(e){
var value = $(this).val();
if(value.length <= 6) {
if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
var amountDots = 0;
var amountCommas = 0;
if(value.indexOf(',') > -1){
amountCommas = value.match(/,/gi).length;
}
if(value.indexOf('.') > -1){
amountDots = value.match(/./gi).length;
}
if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
$(this).val(value.substr(0,value.length - 1));
return false;
}
else{
$(this).val(value.substr(0, value.length - 1) + ',');
}
}
$(this).val(value/100); //here is the value will insert
} else {
$(this).val(value.substr(0,value.length - 1))
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="price" />
Ok, totally different solution that works when deleting characters:
$(document).on('keypress','.price',function(e){
var char = String.fromCharCode(e.which);
if(isNaN(char)) char = '';
var value = $(this).val() + char;
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
var value = $(this).val();
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
});
https://jsfiddle.net/14shzdo5/
With each new keystroke, assuming it's a number, append it to the end, multiply by 10 and display the result.
The following logic works for the basic scenario. You may have to separately handle clearing out the text input.
$(document).ready(function() {
$("#my-input").on('keyup', function(e) {
var v = String.fromCharCode(e.keyCode);
if (!isNaN(v)) {
var dv = $("#my-display").val();
$("#my-display").val(dv + '' + v);
$(this).val(($("#my-display").val() / 100).toFixed(2));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="my-input" />
<input type="hidden" id="my-display" />

Allow only 2 numbers on input type number

How to set a range between 0 and 99 on a input type number? I am using HTML5 attributes ( min="0" max="99" ) but it's not working and as far as I know this kind of attribute is not supported by some browsers.
So I am using this script which blocks non-numerical characters but I want to limit the numbers to a max of 99 (only 2 digits). How can I do that?
Also I want to allow users to use the keyboard to type the numbers.
$(".js-number").numeric();
jsFiddle
<input class="test-input" type="number" maxlength="12" />
<script>
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
var $this = $(this);
var val = $this.val();
var valLength = val.length;
var maxCount = $this.attr('maxlength');
if(valLength>maxCount){
$this.val($this.val().substring(0,maxCount));
}
});
</script>
Your example works if you remove the $(".js-number").numeric();
But you can edit the input.
maxlength attribute works on input type text, so I guess javascript validation is inevitable.
<input type="number" class="js-number" min="0" max="99" value="0">
<script>
$(".js-number").bind('keydown', function(e){
var targetValue = $(this).val();
if (e.which ===8 || e.which === 13 || e.which === 37 || e.which === 39 || e.which === 46) { return; }
if (e.which > 47 && e.which < 58 && targetValue.length < 2) {
var c = String.fromCharCode(e.which);
var val = parseInt(c);
var textVal = parseInt(targetValue || "0");
var result = textVal + val;
if (result < 0 || result > 99) {
e.preventDefault();
}
if (targetValue === "0") {
$(this).val(val);
e.preventDefault();
}
}
else {
e.preventDefault();
}
});
</script>
function format(input){
if(input.value < 0) input.value=Math.abs(input.value);
if(input.value.length > 2) input.value = input.value.slice(0, 2);
$(input).blur(function() {
// if(input.value.length == 1) input.value=0+input.value;
// if(input.value.length == 0) input.value='01';
//* if you want to allow insert only 2 digits *//
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="number" step="1" oninput="format(this)">
It works for me... hope for you as well :)
you can set like this:
<input type="text" class="js-number" maxlength="2">
You can just use maxlength="2" in input of html and this.value = this.value.replace(/[^\d]/, '') in Javascript function
maxlength="2" : It allows only two entries in the input by text (lets take it number) so the maximum two digit number is 99 and minimum two digit number is -9 (- is also considered as a entry) but if - sign is removed than minimum number is 00 , which solves the range of 00-99
Now the input is type=text so any alphabet can be entered along with symbols (- # $...) to solve that JavaScript Regular Expression
this.value = this.value.replace(/[^\d]/, '') : It take the value from the input on each entry of a digit and check if it is a number or not . If it is a number then the entry will be leaved as it is but if entry is not a number than it is replace by '' means removed from the input . So only number entry is solved without a - sign too
document.getElementsByClassName("orderUnits")[0].addEventListener("input", amountofUnits);
function amountofUnits() {
this.value = this.value.replace(/[^\d]/, '')
}
<input type="text" class="orderUnits" maxlength="2">

validating input text field (max and min) based on checkbox condition

What I am trying to do is to apply some validation on an input text field based on a checkbox and whether it is checked or not.
Case 1: when check box is selected, user can only enter numbers from 0 to 100 (decimal included. So 34.35 is allowed)
Case 2: Normal numeric validation
However the behavior of my code in Case 1 is it only allow user to enter 1 nu,beric digit between 1 to 9.
Here is my code.
HTML markup
elements.stakeInput = $('<input placeholder="0.00" type="text" style="float:right" />');
elements.promoMoneyCheckbox = $('<input type="checkbox" />');
JS
elements.promoMoneyCheckbox.click(function() {
SingleDiv.prototype.validatePromoInputField(self);
});
validatePromoInputField : function(singleDiv) {
var self = this,
elements = singleDiv.getElements(),
promoMoneyCheckbox = elements.promoMoneyCheckbox;
if (promoMoneyCheckbox.is(':checked')) {
elements.stakeInput.attr("placeholder", "10.00");
elements.stakeInput.keypress(function(event) {
var num = parseInt(self.value, 10),
min = 0,
max = 100;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
})
}
else {
elements.stakeInput.attr("placeholder", "00.00");
validateInputs(event, 'decimal')
}
}
function validateInputs(event, typeOfInput) {
event = event || window.event;
if (event.ctrlKey || event.altKey || event.metaKey) return;
var regex;
switch (typeOfInput) {
case 'decimal':
regex = /^[.0-9]$/;
break;
case 'minAndMax':
regex = // May be I could add a regex over here instead of the validating in validatePromoInputField fucntion
break;
default:
regex = /^.$/;
break;
}
var char = getKeypressChar(event);
if (char == null || regex.test(char)) return;
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
}
Is there any simple way to achieve this?
I am not looking for HTML5 validation i.e (input type="number" min and max value).
Use jquery .change() event to detect changes of the input and parseInt to verify the input.
$("#in").change(function(e) {
var val = parseInt($(this).val());
if (!isNaN(val)) {
if (val >= 0 && val < 100) {
$("#out").html("good!");
return;
}
}
$("#out").html("bad!");
});
http://jsfiddle.net/VxM4h/1/
Remember that client side changes can be altered. Make sure to verify your input on the server side as well.

How to prevent keypress two digits after a decimal number?

I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});

Categories