How to completely restrict decimal points from being entered in text input? - html

I have been searching through many HTML-related questions here and I am currently using the input tag pattern attribute to validate my inputs. This works by only allowing one or two numbers being input, and does not submit invalid data. However, I would prefer unwanted characters (decimal point and letters) to not be able to be put in the text box at all.

This will do it for you https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/4/
updated fiddle to allow numbers in numlock to work too https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/5/
<input ID="FirstName1" class="test" onkeydown="return Fname(event);">
<script>
function Fname(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
//checks for invalid keystrokes (numbers only)
if (charCode > 57 || charCode < 48) {
return false;
} else {
return true;
}
}
</script>

Related

IE 11 not respecting input number and allowing non numeric values to be entered

The browser IE 11 is allowing non-numeric values to be entered into a number input. I have tested in other browsers such as Chrome and Firefox and they are respecting the number input.
This image shows how in IE 11 the user can enter a comma and the letters "gal".
<div class>
<input type="number" min="0" onkeydown="return event.keyCode !== 69" class="form-control questTxt" value="">
</div>
Is number input not supported in IE 11? This resource appears to show that it does?
LINK TO RESOURCE
As epascarello said, the type attribute is there for validation purposes, so if you enter text into a number field and try to submit a form, it will not let you. I couldn't tell you why that's not default for a number input, but browser compatibility has been a pain ever since browsers existed.
If you want to the user to actually be unable to enter anything except for numbers, you can do it in JavaScript.
const inputField = document.querySelector("input");
inputField.addEventListener("keypress", e => {
if (e.which > 31 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
}
});
Looks like IE 11 browser has some issues with Input type Number.
You can refer to the known issues for the IE browser on the CanIuse site.
As a workaround, you can use this JS function.
function handleKeyPress(e) {
let newValue = e.target.value + e.key;
if (
// It is not a number nor a control key?
isNaN(newValue) &&
e.which != 8 && // backspace
e.which != 17 && // ctrl
newValue[0] != '-' || // minus
// It is not a negative value?
newValue[0] == '-' &&
isNaN(newValue.slice(1)))
e.preventDefault(); // Then don't write it!
}
Insert a number:
<input onKeyPress="handleKeyPress(event)"/>
Reference:
input type=“number” not working in IE browser

Angular6 - Custom Input field

I have to create input field in Angular, that input field allow only number with 2 decimal places like '123455.12'
Below is what i have tried so far
<input myCustomDirective type="text">
I created Directive. In my CustomDirective I used HostListener for keypress event in that listener i used regular expression to validate but it allow only number it not allowing to enter '.(dot)'
new RegExp('^[0-9]*$');// my regular expression
Here's a Directive that takes Only Decimal Values with custom
precisions.
https://stackblitz.com/edit/angular-decimal-directive
It will allow you to put digits before the .(dot)
It will not allow you to paste (ctrl+v) non-decimal.
It will take single .(dot) . by default it will take 2 digit after the . (dot).
Example:
`<input type="text" [(ngModel)]="myVar" decimal>`
But you can define the precision size like that :-
`<input type="text" [(ngModel)]="myVar" [decimal]="3">`
If you want to use Only Integer not floating point you can use the Directive Like this:
<input type="text" [(ngModel)]="myVar" [decimal]="0">
If you don't complete enough precision in the input , then it will
automatically complete rest of the number precision (also if a .(dot)
needed) by onblur event.
You Can't inject string value by two way binding.
N.B: [(ngModel)] is mandatory for using the Directive.
ng-pattern that you reguire is ng-pattern=" /^[.\d]+$/"
Please check out the fiddle jsfiddle.net/gsferreira/Lsv9f0b0 , posted in link ,
ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" is the key
From Plain Old Java script fiddle link https://jsfiddle.net/j3cbytws/
Only numbers please and a single dot allowed , nothing else:
<input type="number" name="someid" onkeypress="return isNumberKey(event)" />
<script>
var isDecimalAlredyEcountered = false;
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if(isDecimalAlredyEcountered && charCode === 46)
return false;
if(charCode == 46)
{isDecimalAlredyEcountered =true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)&& charCode != 46)
return false;
return true;
}
</script>
There can be an issue of backspace char and delete with the above implementation, so you have to reset the state on clear

Restrict decimal entries in html textbox

I have an HTML Textbox where the user will input data, which in turn will be saved in an SQLcolumn of type decimal(12,4). How will I restrict my textbox to allow either number or decimal value of above-mentioned precision?
This is my textbox code:
#Html.TextBoxFor(m => m.Rate, null, new {#maxlength = "12", style = "width:87px;"})
there is a same question with a proper answer please refer to this link.
link
the answer of this question on the link take only decimal point and if you want number as well with the decimal points.just remove the not sign (!) in this line.
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;

Chrome clearing input type=number

In the latest release "47.0.2526.73" all my input type="number" are clearing every time that we try to type a float point number, example : 1.1
These inputs have a keyup event handler in jQuery to remove the leading zeros.
This code was working before the latest update.
Is there a bug?
-- UPDATE --
//Fix to leading zero decimals
$('input[type=number]').keyup(function (e) {
if (!this.value && (e.keyCode == 190 || e.keyCode == 110)) {
this.value = '0.';
}
});
This is the code that is not longer working
Change the step so it don't use the default '1' and uses a float. It will allow you to use float numbers and not only integers.
Ex: '0.1'
Looks like chrome is no longer allowing you to read/set the input value for number types using the keyup event when it is in the middle of the decimal point typing.
This is when the user type just '.', you cannot get the value '1.' or set it the same way in the event.
What I did was change the logic to:
$('input[type=number]').keyup(function (e) {
if (this.value) {
if (this.value.charAt(0) == '.')
{
this.value = '0' + this.value;
}
}
});
This is the only way that I have found to fix typing a number without the leading zero in the input box

HTML5 input type number not working in firefox

I am using HTML5 input type=number. Its working perfectly in Chrome browser, but its not working in Firefox and IE9.
I want to increment the quantity by one i.e. step=1 and also I have set min=1.
I am using the following code:
<form action="" class="cart" method="post" enctype='multipart/form-data'>
<div class="quantity">
<input type="number" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" />
</div>
<button type="submit" class="single_add_to_cart_button button alt">Add to cart</button>
</form>
Is there any patch or hack to make it work in Firefox and IE9. Or else, what could be the possible solution for that.
It is not supported in firefox or internet explorer, except for version 11 which has partial support. See this comparison matrix.
You can use the number polyfill shim to get support for unsupported browsers.
Alternately, you can use a textfield with a pattern="" attribute. Although it doesn't have the up and down buttons, it does validate for having the correct values:
<input type="text"
name="quantity"
pattern="[1-9]"
value="1"
required
title="Qty"
class="input-text qty text"
/>
You can alter the pattern to your quantity wishes, it is now set for a value ranging from 1 to 9. Also you can add up/down buttons with JS/jQuery that have hotkeys bound to them for a more number-field-like feel.
For React I have used a simple and clean implementation to forbid letters in Firefox/Safari/Chrome etc...
<input type="number" onKeyDown={(event) => checkIfNumber(event)} />
checkIfNumber(event) {
/**
* Allowing: Integers | Backspace | Tab | Delete | Left & Right arrow keys
**/
const regex = new RegExp(/(^\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/);
return !event.key.match(regex) && event.preventDefault();
}
Allowing more keys:
By logging the event.key in the console you are able to check the actual value of the pressed key while then adding it to the regex using a pipe | symbol.
Keep in mind that this solution only allows Integers, if you want to allow floating numbers(decimals) use the following regex pattern
regex = new RegExp(/(^\d*\.?\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/)
You can build and check your regex pattern here:
https://regex101.com/
The input type number is not supported yet in Firefox or IE9 (almost in IE10), so it will revert to input type text.
See this compatibility chart.
There's really no need for a "patch or hack" - a regular input field will work just fine. That's why it reverts to a text field. Whether or not it displays as an actual number field to the end-user is just a bonus to make it slightly more convenient. You should still be doing server-side checks on whatever value is sent to you, so allowing a user to just type in a number when their browser doesn't support the number type shouldn't harm anything.
It's not supported.
You can use javascript for the same result if you really need it.
There are lot of examples :
Increment value of textinput with jquery like spinner
I am using firefox, I had the same issue developing my input type number typing characters and spaces etc...
anyway I am using angular 2 in this example, it's almost similar to JavaScript, so you can use this code in every case :
here is the html :
<input class="form-control form-control-sm" id="qte" type="number" min="1" max="30" step="1" [(ngModel)]="numberVoucher"
(keypress)="FilterInput($event)" />
here is the function FilterInput :
FilterInput(event: any) {
let numberEntered = false;
if ((event.which >= 48 && event.which <= 57) || (event.which >= 37 && event.which <= 40)) { //input number entered or one of the 4 directtion up, down, left and right
//console.log('input number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
numberEntered = true;
}
else {
//input command entered of delete, backspace or one of the 4 directtion up, down, left and right
if ((event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 46 || event.which == 8) {
//console.log('input command entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
}
else {
//console.log('input not number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
event.preventDefault();
}
}
// input is not impty
if (this.validForm) {
// a number was typed
if (numberEntered) {
let newNumber = parseInt(this.numberVoucher + '' + String.fromCharCode(event.which));
console.log('new number : ' + newNumber);
// checking the condition of max value
if ((newNumber <= 30 && newNumber >= 1) || Number.isNaN(newNumber)) {
console.log('valid number : ' + newNumber);
}
else {
console.log('max value will not be valid');
event.preventDefault();
}
}
// command of delete or backspace was types
if (event.keyCode == 46 || event.which == 8) {
if (this.numberVoucher >= 1 && this.numberVoucher <= 9) {
console.log('min value will not be valid');
this.numberVoucher = 1;
//event.preventDefault();
this.validForm = true;
}
}
}
// input is empty
else {
console.log('this.validForm = true');
this.validForm = false;
}
};
in this function I had to just let the keypress of numbers, direction, deletes enter.
To allow only number and points to be written in an input we have to get the value of the pressed key and compare it with a REGEX (test() method), otherwise the event isn't executed.
const input = document.getElementById("numberInput");
input.addEventListener("keypress", e => {
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && e.key == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
}
}
}
Also I created a function that allows writing a maximum of three whole numbers and two decimal numbers.
I hope it helps you.
I usually post information that has helped me or some solutions on my twitter (#PabloAndresValC)
input.addEventListener("keypress", e => {
const keyValue = e.key;
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && keyValue == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
} else {
// If the number has one or two whole numbers and a point, another
// point won't be printed
if (/[0-9]{1,2}[.]/.test(e.target.value) && keyValue == ".") {
e.preventDefault();
}
// If the number has one or two whole numbers and a point
else if (/[0-9]{1,2}[.]/.test(e.target.value)) {
// We can write up to two more numbers after the point
if (/[0-9]{1,2}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
// If there are 3 numbers and we press another, a point
// will be printed automatically
// And we can write up to two more numbers after the point
else if (/[0-9]{3}/.test(e.target.value) && keyValue != ".") {
e.target.value += ".";
if (/[0-9]{3}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
}
}
});
Note: The min attribute of the tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.
Note: The min attribute will not work for dates and time in Internet Explorer 10, since IE 10 does not support these input types.
Source: http://www.w3schools.com/tags/att_input_min.asp
Firefox 89.0 solves this problem.
I think this is the best practice in my previous projects experience.
This solution worked on Firefox, Safari and other not support input[type=number] realized browsers.
document.querySelector('#number-input').addEventListener('keydown', function(evt){
!/(^\d*\.?\d*$)|(Backspace|Control|Meta|a)/.test(evt.key) && evt.preventDefault()
})
<html>
<input type="number" id="number-input"/>
</html>
<input
type="text"
class="form-control"
#keypress="getMobileNumber($event)"
/>
//Function
function:getMobileNumber(e){
let char = String.fromCharCode(e.keyCode); // Get the character
if (/^[0-9]*$/.test(char)) return true;
// Match with regex
else e.preventDefault(); // If not match, don't add to input text
},