Javascript currency regular expression replace - javascript

For my business web application I want a user to only be able to enter valid currency values in a textbox.
Currently I use
$input.val($input.val().replace(/[^.\d]/g, ''));
But this doesn't take in consideration order or multiple decimal seperators.
So the user either has to enter a whole integer or a valid decimal value e.g.:
49
49.50
Bonus points if this is allowed too:
.50 (for 0.50)
So I don't want to validate, I want to restrict typing into the textbox. Is this possible with a single regexp replace?

We can do this in two steps. Restrict the user to type only the number characters and . character.
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode < 31 && (charCode > 48 || charCode < 57))
return true;
return false;
And the next one is for allowing the .:
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
return true;
return false;
The next step will be not allowing double periods.
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
if (charCode == 46 && value.indexOf(".") !== false)
return true;
return false;
Hope you can have this as a starting point.
Snippet
Open Deal: Break it if you can.
function check(inp) {
var charCode = (event.which) ? event.which : event.keyCode;
console.log(charCode);
if (charCode == 8)
return true;
if ((charCode > 46 && charCode < 58) || (charCode > 95 && charCode < 106) || charCode == 110 || charCode == 190)
if (charCode == 110 || charCode == 190)
if (inp.value.indexOf(".") == -1)
return true;
else
return false;
else
return true;
return false;
}
<input type="text" onkeydown="return check(this);" />

It's more user friendly to advise of errors and let users fix them themselves. You might consider using the keyup event, but showing an error too early (before the user has had a chance to enter a valid value) can be annoying too. e.g.
function validate(el) {
var type = el.className;
var errEl = document.getElementById(el.name + 'Err');
if (type == 'typeCurrency') {
var currencyRe = /^-?(\d+(\.\d{1,2})?|\.\d{1,2})$/;
errEl.style.visibility = currencyRe.test(el.value)? 'hidden' : 'visible';
}
}
.errorMessage {
color: red;
background-color: white;
visibility: hidden;
}
Cost <input onblur="validate(this)" name="foo" class="typeCurrency" placeholder="0.00"><br>
<span id="fooErr" class="errorMessage">Please enter a valid cost, e.g. 2.45</span>

Related

Enter only digits in a textbox

I was using this function to enter only digits in to textbox and it worked.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
but customer asked me to restrict - sign so user should not enter - sign. So I modified the code to this:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode == 45)
return false;
return true;
}
and now it not works, it allows letters too, why?
You need || in the group:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var bool = (charCode > 31) && (charCode < 48 || charCode > 57 || String.fromCharCode(charCode) == "-");
return !bool;
}
<input type="text" onkeypress='return isNumberKey(event)'>
You should use || instead of && in your test.
On my azerty keyboard, the - sign charcode is 54, not 45.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode == 45) )
return false;
return true;
}
See this fiddle
Edit
Looks like your charCode is correct. The 54 value comes from my azerty keyboard.
Nevertheless, you should use || instead of && in your check.

How my JS function would restrict specific data ?

In asp.net textbox I have called a javascript function which I wrote to restrict only 'digits' entry in text box but I also want to allow '+' sign but can't solve it.
This is what I have tried so far.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Just reverse your condition and add the ASCII code for + which is 43 to return true
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode >=48 && charCode <= 57) || (charCode == 43))
return true;
return false;
}
If you were able to restrict digits, you can also enter '+', I guess you need ASCII table and corresponding value i.e. how you were restricting digits, and charCode > 31 seems useless if you are checking for digits only:
http://www.asciitable.com/
so if you want to check for +
charCode != 43
You need to check for + as well explicitly, modify your if to :
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 43)
Here is working example:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 43) {
return false;
}
return true;
}
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
Working Demo
Ascii Table
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)&& charCode != 43) {
return false;
}
return true;
}

SHIFT+HOME and SHFT+left/right keys for text fields not working

I am using Struts2 <s:textfield /> tag and the below code calculates and checks / validates the value entered in the text field on the fly with JS.
It also updates the total entered in textfield list, these are handled by onblur and onkeydown events as below.
<s:textfield id = "fieldid"
name = "xyz"
onblur = "javascript:calculateTotal()"
onkeydown = "javascript:checkDecimal(this); return checkDecimal(event);"
/>
By using this code SHIFT+HOME , SHIFT+Left and SHIFT+Right keys functionalities are not working.
Is there any possibilities that this is due to onblur and onkeydown events ?
function checkDecimal(evt) {
var charCode;
var version = msieversion();
if(version==8){
charCode = (window.event) ? evt.keyCode : evt.which;
charCode = (window.event) ? evt.keyCode : evt.which;
}else{
charCode = (evt.which) ? evt.which : evt.keyCode;
}
if (!evt.shiftKey) {
if ((charCode >= 48 && charCode <= 57) ||
(charCode == 8) ||
(charCode == 46) ||
(charCode == 190) ||
(charCode == 35 ) ||
(charCode == 36) ||
(charCode == 9) ||
(charCode == 37) ||
(charCode == 39) ||
(charCode >= 96 && charCode <= 105) ||
(charCode == 110))
{
return true;
} else {
return false;
}
} else {
if (charCode == 9) {
return true;
} else {
return false;
}
}
}
You need to use the keypress event instead of the keydown one.
The keypress will intercept the resultant character,
while the keydown will interpret the SHIFT as a button itself.
Then try using
<s:textfield id = "fieldid"
name = "xyz"
onblur = "javascript:calculateTotal()"
onkeypress = "javascript:checkDecimal(this); return checkDecimal(event);"
/>
Code will look like this...
if (!evt.shiftKey) {
if ((charCode >= 48 && charCode <= 57) ||
(charCode == 8) ||
(charCode == 46) ||
(charCode == 190) ||
(charCode == 35 ) ||
(charCode == 36) ||
(charCode == 9) ||
(charCode == 37) ||
(charCode == 39) ||
(charCode >= 96 && charCode <= 105) ||
(charCode == 110))
{
return true;
} else {
return false;
}
} else if(evt.shiftKey) {
if ((charCode == 35 ) || (charCode == 39) || (charCode == 37) || (charCode == 36)) {
return true;
}
}
I assume you need to validate and allow only the decimal values. In that case this snippet will do the job.
<input id = "fieldid"
name = "xyz"
onblur = "javascript:calculateTotal()" onkeypress="return checkDecimal(event);" />
<script>
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function checkDecimal(evt) {
var charCode = (window.event) ? evt.keyCode : evt.which;
var currentVal = String.fromCharCode(charCode);
var val = document.getElementById(evt.currentTarget.id).value + '' + currentVal;
return (evt.shiftKey || isNumeric(val) || isNumeric(currentVal) || String.fromCharCode(currentVal) == '.');
}
</script>
Please feel free to correct me if I was not read the question correctly.

onkeypress event in Firefox

I'm looking for a solution for a (as it seems) common problem.
I want JavaScript to check a specific format when entering data in a input-field.
This is what I've got:
HTML:
<input onkeypress=" return fieldFormat(event)">
JavaScript:
<script type="text/javascript">
//Checks spelling in realtime, if JavaScript is enabled.
function fieldFormat(event){
var charCode = (window.event) ? window.event.keyCode : event.keyCode;
var parts = event.target.value.split('.');
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
return false;
return true;
}
</script>
This works fine in Chrome and IE. But for some reason, Firefox gives me troubles ^^
Any hints?
Some browsers use keyCode, others use which, so try this:
function fieldFormat(event){
var e = event || window.event,
charCode = e.keyCode || e.which,
parts = e.target.value.split('.');
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
return false;
return true;
}
Check this one - seems like it's common https://support.mozilla.org/pl/questions/998291

Allow user to paste numeric values either by ctr+c ctr+v OR by right click copy paste

I want to copy paste numeric values in this field, can we achieve this keeping onkeypress as it is?
HTML:
<input type="text" onkeypress="return allowNumOnly(event);">
Javascript:
function allowNumOnly(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode
console.log(charCode);
if(charCode==36 || charCode==46 || charCode==37 || charCode==39)
return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

Categories