How to replace an input text value in order to match a currency type input - javascript

I have a complex problem with a simple input. I want the user to enter an amount of money, so I naturally thought of using a number type. The problem is that I live in Europe and decimals are written with commas(and so the number input will automatically add a comma as separator), but my backend logic expects dots for the cents.
After looking everywhere for alternatives to this problem, I only found I could use a text input and check the user's input with a chain of .replace to test that the user is only entering numbers and eventually a dot followed by only two numbers for the cents.
This is the code we created so far:
export const onChangeCustomInput = (e) => {
let value = e.target.value
value = value
.replace(/[A-Za-z]+$/g, '')
.replace(/,/g, '.')
.replace(/ /g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
.replace(/[.\s]{2,}/, '.')
.split('.')
if (typeof value === 'object' && value.length > 1) {
value[1] = value[1].substr(0, 2)
if (value.length === 3) {
value.splice(2, 1)
}
value = value.join('.')
}
e.target.value = typeof value === 'object' ? value[0] : value
}
this is very heavy (and ugly) code, and Sonar check failed saying this may lead to Denial of Service attack (?...).
Is there a better way to manage this case in vanilla javascript?

Can you try toLocaleString?
Basically if you have a number You can set in which kind of country you're using it.
So, you can show as an EU number, but send to the backend in the other format.
One example:
var number = 35001235.12
number.toLocaleString('en-US') // returns '35,001,235.12'
number.toLocaleString('de-De') // returns '35.001.235,12'
You can read more in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

You could try using valueAsNumber property of the input element. The value is numeric so it shouldn't matter what was entered by the user. If the input is wrong it takes the value of NaN.

You can use the package Inputmask, it works perfect for your use case, you will use this regex [0-9]*\.[0-9]{2} to match your example
$(document).ready(function(){
Inputmask().mask(document.querySelectorAll("input"));
});
<script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.js"></script>
<input data-inputmask-regex="[0-9]*\.[0-9]{2}" />

Related

toString().length on a number with zeros and only zeros always returns 0

I'm working on a page that accepts 4 digits (exactly 4 digits) pin from users. Something like this.
<input type="number" ng-model="passCode" class="form-control" onpaste="return false" id="passCodeField" ng-disabled="!enablePassCode" ng-change="onInputPasscode()" ng-keypress="onKeyPressPasscode($event)"/>
onKeyPressPasscode function
$scope.onKeyPressPasscode = function($event) {
if(isNaN(String.fromCharCode($event.which || $event.keyCode))){
$event.preventDefault();
}
}
onInputPasscode() function :
$scope.onInputPasscode = function() {
if ($scope.passCode.toString().length > 4){
$scope.passCode = $scope.passcode;
}
if($scope.passCode.toString().length == 4) {
$scope.passcode = $scope.passCode;
$scope.disableContinue = false;
session.put('pinFlow',true);
} else {
console.log("current length - " + $scope.passCode);
$scope.disableContinue = true;
session.put('pinFlow',false);
}
}
This is failing when the input is all zeros. i.e current length is not getting updated hence the user is allowed input as many zeros as he wants. How do I take 4 digit zeros as input and still meet the checks that I have?
This is in angular 1.5.8v. And I'm not an expert in AngularJS. So any help would be appreciated. Also, please let me know if need any other info. I'll update the answer accordingly.
Thanks in advance.
It's not possible to do this with a an input with type set to number.
When user enters a number 0001, that's actually 1.
Things like PINs should be handled with type set to text.
You can then use a regex for validation.
To allow exactly four digits, no more and no less, use the following regex:
^\d{4,4}$
From JavaScript, use this regex to test a string, like the following:
/^\d{4,4}$/.test('1234')
// => true
/^\d{4,4}$/.test('123456')
// => false
/^\d{4,4}$/.test('12')
// => false
The cause of your problem is that if you PIN Scheme allows for leadings zeros, number is not the ideal type for this (because in numbers, leading zeros can be omitted without changing meaning).
Instead, use input type=text or probably even better, input type=password. Also, I wouldn't listen to keypress - instead use the input event.

Validating numeric input while formatting numeric input

In an asp.net-mvc project using C#.
I use a function to format larger numbers with commas such as 1,000,000, thanks to this post:
function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
The issue is, I have the inputs locked down to accept only numbers with a min value of zero.
<input type="number" min="0" class="myclass" value="#somevalue" />
This poses a problem using the JS, as it needs only number input. Which brings me to a question like this How to make HTML input tag only accept numerical values?, which also offers a JS solution.
I'm wondering if anyone has developed an elegant way to format numeric input display, while validating numeric input, is there are any other options available here? It doesn't have to purely be a JS solution.
You can't use the numeric input, because, well, JavaScript doesn't consider formatted number to be a number.
The option is to use the non-numeric input but filter out any "problematic" chars.
In the following example, I'm also handling the dot separator in case you need to accept fractions.
As the text box is being edited, it also has to preserve the cursor position. I've achieved it there with the help of Updating an input's value without losing cursor position.
function format(inp){
var start = inp.selectionStart, // get the selection start
end = inp.selectionEnd; // and end, as per the linked post
var s1=inp.value.split(",").length-1; //count the commas before edit
inp.value=numberWithCommas(inp.value.replace(/,|[^\d.]/g,''));
var s2=inp.value.split(",").length-s1-1; //count the commas after edit so as to know where to place the cursor, as the position changes, if there are new commas or some commas have been removed
inp.setSelectionRange(start+s2, end+s2); // set the selection start and end, as per the linked post
}
function numberWithCommas(str) {
var a=str.split('.');
var p=/\B(?=(\d{3})+(?!\d))/g;
if(a.length>1)
return a[0].toString().replace(p, ",")+"."+a[1];
else
return str.toString().replace(p, ",");
}
<input onkeyup="format(this)">
I have the answer of your first question.
You can disable all keys rather than only numbers keys.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 43 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
I also created working demo on jsfiddle
The program flow:
Getting the input via an on change event and calling the other functions, showing passing the data through a Ajax POST.
$('.Amount').on("change", function (e) {
var myInput = $(e.target);
var input = this.value;
// Remove any non digits (including commas) to pass value to controller.
var Amount = validateInput(input);
// Format the string to have commas every three digits 1,000,000 for display.
var val = numberWithCommas(Amount);
$(myInput).val(val);
$.ajax({
type: 'POST',
dataType: "json",
url: somesUrl + '/' + somethingelse,
data: JSON.parse('{"Amount": "' + Amount + '"}'), // Amount is a nice format here and will not throw an error.
// TODO etc
});
});
Remove any non numbers and give a value of zero if no numbers are inputted.
var validateInput = function (input) {
input = input.toString().replace(/[^0-9]/g, "");
/* Remove leading zeros. */
input = input.replace(/^0+/, '');
if (input == "")
input = 0;
return input;
}
Format the input with commas 1,000,000,000.
function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
So even if the user types input with commas e.g. 1,734,567 it will work and if they misplace where they put a commas e.g. 17,35,555 it will still validate.
See working fiddle.
I actually worked out a nice solution while trying to meet project deadlines and in part this was solved by this answer by nicael.
This solution does not check the input as it is being typed, but after it is finished, I chose the change event, as opposed to the input event, as it calls the function once and (similar to a submit event) than validates the input in one call. Removing any commas and non digits; solving the issue of formatting with commas, by removing them for the ajax call, then reformatting it with commas for the display. There is a check to remove leading zeros.
If all the input is garbage I replace this value with zero to prevent an error passing to the controller with null data (just a design choice, could display a toast message instead).

How to validate a decimal value input?

Currently working on only decimal values where in the text field user enter only deciaml value. Should accept only 10 numbers for example if user enter 12345.000000 it should get an alert says Number field format error. Please re-enter using the proper format. (6.3)
With my current jquery code it will accept decimal value
$("#txtQty").keyup(function() {
var $this = $(this);
$this.val($this.val().replace(/[^\d.]/g, ''));
});
This is my html code for the text box with this html it will allow only 10 character
<input id="txtQty" type="text" maxlength="10"/>
I tired the below SO user told but still I am getting the same issue
$('#txtQty').focusout(function(e) {
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
}
});
before decimal point it has to accept (1-6) 6 number after decimal point it has to accept 3 only zero's if wrongly typed it should throw an alert not at all working still not getting that
Here is the fiddle link for the same
123456.000 -- true
12345.000 -- true
1234.000 -- true
123.000 -- true
12.000 -- true
1.000 -- true
Thanks in advance
$('.ipt_Havg').focusout(function (e) {
var regexp = /\d*\.\d{3}/
if (document.getElementById("ipt_Havg").value !== regexp) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
});
1) Your if/else is broken...
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null // <- comparison makes no sense here
}
You are incorrectly using a comparison operator in place of a "statement" within the else. The else needs to contain a "statement" (something to do) not another comparison operator.
See: MDN "if...else" documentation
If some condition is true then do something, otherwise do something else.
if ('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
2) NOTE: I previously thought this was too obvious to even mention, however, you've hard coded '123456.789' into the conditional. In other words, it will never matter what value gets entered into your form...
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) is always going to be true since '123456.789' is the only value being used here.
Otherwise, use the value of the field...
$('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null
3) Your logic was also backwards.
if ($('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null) {
alert('nothing wrong here');
} else {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}
DEMO: http://jsfiddle.net/wfzv0h5y/
4) Incorrect regex...
but one small mistake in the end it has to accept only three zero not more than tht but now if i enter 1234.0000 still it was accepting
Your regex also needed fixing...
^\d{1,6}\.0{3}$
DEMO: http://jsfiddle.net/wfzv0h5y/6/
JQuery Number Formatter Plugin is a good alternative in your situation.
https://github.com/andrewgp/jsNumberFormatter
You can check your input through this and validate the way you want.
You could use HTML5 input number:
<input type='number' step='0.001' max="999999.999" />
The step= sets the decimal places, the max= guarantees the other side.
You can specify repetitions in RegExps:
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
true
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
false

Javascript Regex for Decimal Numbers - Replace non-digits and more than one decimal point

I am trying to limit an input to a decimal number. I'd like any invalid characters not to be displayed at all (not displayed and then removed). I already have this implemented but for whole integers (like input for a phone number) but now I need to apply it for decimal input.
Sample input/output:
default value 25.00 -> type 2b5.00 -> display 25.00
default value 265.50 -> type 2.65.50 -> display 265.50 (as if prevented decimal point from being entered)
default value 265.52 -> type 265.52. -> display 265.52 (same as previous one)
End New Edit
I found many threads that dealt with "decimal input" issue but almost 99% of them deal only with "match"ing and "test"ing the input while my need is to replace the invalid characters.
Other than trying many regexes like /^\d+(\.\d{0,2})?$/, I also tried something like the below which keeps only the first occurrence in the input. This still isn't my requirement because I need the "original" decimal point to remain not the first one in the new input. This was the code for it:
[this.value.slice(0, decimalpoint), '.', this.value.slice(decimalpoint)].join('')
This thread is the closest to what I need but since there was no response to the last comment about preventing multiple decimal points (which is my requirement), it wasn't useful.
Any help would be appreciated.
Outline: find the first ., split there and clean the parts, else just return cleaned value.
function clean(string) {
return string.replace(/[^0-9]/g, "");
}
var value = "a10.10.0";
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
var part1 = value.substr(0, pos);
var part2 = value.substr(pos + 1);
result = clean(part1) + "." + clean(part2);
} else {
result = clean(value);
}
console.log(result); // "10.100"

Getting a integer value from a textbox, how to check if it's NaN or null etc?

I am pulling a value via JavaScript from a textbox. If the textbox is empty, it returns NaN. I want to return an empty string if it's null, empty, etc.
What check do I do? if(NAN = tb.value)?
Hm, something is fishy here.
In what browser does an empty textbox return NaN? I've never seen that happen, and I cannot reproduce it.
The value of a text box is, in fact a string. An empty text box returns an empty string!
Oh, and to check if something is NaN, you should use:
if (isNaN(tb.value))
{
...
}
Note: The isNaN()-function returns true for anything that cannot be parsed as a number, except for empty strings. That means it's a good check for numeric input (much easier than regexes):
if (tb.value != "" && !isNaN(tb.value))
{
// It's a number
numValue = parseFloat(tb.value);
}
You can also do it this way:
var number = +input.value;
if (input.value === "" || number != number)
{
// not a number
}
NaN is equal to nothing, not even itself.
if you don't like to use + to convert from String to Number, use the normal parseInt, but remember to always give a base
var number = parseInt(input.value, 10)
otherwise "08" becomes 0 because Javascript thinks it's an octal number.
Assuming you have a reference to the input text box:
function getInteger(input) {
if(!input || !input.value) return "";
var val = parseInt(input.value, 10);
if(isNaN(val)) return "";
else return val;
}
One thing you could do is a regex check on the value of the textbox and make sure it fits the format of an accepted number, and then if it fits the format perform your process, otherwise return an empty string.
Edit: This is an example from some code I have in front of me (might not be the best regular expression):
var anum=/(^\d+$)/;
if (!anum.test(document.getElementById("<%=txtConceptOrderValue.ClientID %>").value))
{
alert("Order Value must be a valid integer");
document.getElementById("<%=txtConceptOrderValue.ClientID %>").focus();
return false;
}
Edit 2: I should also note that I am using ASP.NET which is why I have the slightly funky way of accessing the textbox. In your regular JavaScript case it may not be as cluttered.

Categories

Resources