Enter only digits in a textbox - javascript

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.

Related

Function for alpha and single space only

I have a function to make people enter alphabet only onkeypress
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
return true;
}
I have another function to prevent them from typing double spaces
function checkstuff(event){
if(event.target.value.substr(-1)=== ' ' && event.code === 'Space')
{
//alert('space clicked twice');
//remove space from the last.
event.target.value = event.target.value.substr(0,event.target.value.length-1);
}
debugger;
var evt = (event) ? event : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
console.log(charCode)
return false;
}
console.log('valid '+charCode)
return true;
}
I've been trying to put the two together into one function with no success. I tried running them both onkeypress, but it only runs the first. How can I merge the 2 functions?
After the part of alphabetical checking, you can add the function to check the double spaces as follows.
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
if(evt.target.value.substr(-1) === ' ' && evt.keyCode === 32) {
return false;
}
return true;
}
<input type="text" onkeypress="return isAlfa(event)" />
Use state for the previous input
const spaceCode = 32;
var lastCharCode = undefined;
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (lastCharCode == spaceCode && charCode == spaceCode) {
throw new Error('No double space allowed');
}
lastCharCode = charCode;
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
return true;
}

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;
}

Javascript currency regular expression replace

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>

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.

Javascript validation works in Google Chrome but not in Firefox

Here is the js code
function isCharKey(evt){
var charCode = event.keyCode
if ((charCode > 64 && charCode <91 )|| (charCode >96 && charCode<123) || (charCode==32))
return true;
return false;
}
Here is the html code
<label id="exe_form_name">Name:</label><input type="text" name="tbcust_name" id="name1" onkeypress="return isCharKey(event);">
Change
var charCode = event.keyCode
to
var charCode = evt.keyCode
function isCharKey(evt)
{
var charCode = evt.keyCode
if ((charCode > 64 && charCode <91 )|| (charCode >96 && charCode<123) || (charCode==32))
return true;
return false;
}

Categories