Javascript text field validation || Money input - javascript

I currently have this validation but when pressed numerous times the input sometimes get pass.
Text field ID : service-rate-amount
$('#service-rate-amount').keyup(function() {
var val = $(this).val();
var checkIf50or00cents = new RegExp("^[0-9]+(\.([0,5]{1})?([0]{1})?)?$");
var limitDigits = new RegExp("/^\d{0,3}(\.\d{1,2})?$/");
if(isNaN(val) && val != "."){
showMessageModal("Only numeric characters are accepted");
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2) {
val = val.replace(/\.+$/,"");
showMessageModal("Only one decimal point is accepted");
}
} else if (!checkIf50or00cents.test(val)){
val = val.slice(0,-1);
showMessageModal("Only 50 cents or 00 cents are allowed");
}
if (!(/^\d{0,3}(\.\d{1,2})?$/.test(val))) {
if(val.length == 4){
if( val.charAt(3) != "."){
val = val.slice(0, -1);
showMessageModal("Only three digits before decimal point is accepted");
}
}
}
$(this).val(val);
});
I want to have a input field that will accept ....
00.50 up to 999.50
I need in increments of .50 centavos, Sorry for my bad english

If you parse the value into a number that can be compared you could remove some of the complexity. see comments below
var dollars = document.querySelector('#dollars');
function checkDollarInput(){
var value = parseFloat( dollars.value ),
valueInt = parseInt( value );
if( dollars.value.match(/[^0-9.-]/) ){
showMessageModal('please use only numbers', value);
return false;
}
// check the max value
if( value > 999.5 ){
showMessageModal('over max value', value);
return false;
}
// check the min value
if( value < 0.5 ){
showMessageModal('under min value', value);
return false;
}
// ensure the correct decimal using modulo division remainer
if( value % valueInt !== 0 && value % valueInt !== .5 ){
showMessageModal('needs to be .0 or .50', value );
return false;
}
console.log( 'success', value );
// all tests have passed
return true;
}
// im only logging value for the sake of testing
function showMessageModal( message, value ){
console.log.apply(console, arguments);
// do something to show the modal
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
I want to have a input field that will accept .... 00.50 up to 999.50
<form id="form">
<input id="dollars" type="text" value="40.50" />
<input id="submit" type="button" value="checkDollarInput" onclick="checkDollarInput()" />
</form>

You could filter away all textual input via the use of input with type number.
HTML
<input id="validate" type="number">
JavaScript
document.getElementById("validate").addEventListener("keyup", function(e) {
var v = Number(this.value);
if(v >= 0.5 && v <= 999.5) {
var decimals = (v % 1).toFixed(2);
if(decimals == 0 || decimals == 0.5) {
console.log("Acceptable");
}
}
}, false);

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" />

Validation with total 4 digit and only 2 digit after decimal

I need to validate some data in java script where I can enter values >= 0.25 to 99.0 and Only 2 digit after decimal.
Here is an example of how you can do it:
frm.onsubmit = function () {
var value = frm.num.value;
if (+value >= 0.25 && +value <= 99 && /^\d+(\.\d{0,2})?$/.test(value)) {
msg.textContent = 'ok';
return false; // remove this to allow submission to happen
} else {
msg.textContent = 'not valid';
return false;
}
};
<form id="frm">
<input name="num"> <span id="msg"></span><br>
<button>Validate and Submit</button>
</form>

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