I want to limit the input type number to maximum 5 numbers, I am using below code, which is working well, only issue is that for backspace I have to use event.keycode which I dont want to use. Is there any alternative apart from usking keycode of backspace.
var input = document.getElementById('input');
input.addEventListener('keypress',showData,false)
function showData(event)
{
if(event.target.value.length<=5)
{
return true;
}
else
{
event.preventDefault();
}
}
If you want it so if the user tries to type more than 5 numbers it only keeps the 5 numbers:
input.oninput = function() {
if (this.value.length > 5) {
this.value = this.value.slice(0,5);
}
}
Why don't you just use:
<input type="number" max="99999">
This will still not stop a user from manually entering a value larger than 99999, but the input element will be invalid.
<input type="number" max="99999" />
How can I limit possible inputs in a HTML5 "number" element?
<form>
<input required type="text" name="inputname" pattern="[0-9]{5,}">
<input type="submit" value="submit">
</form>
Related
I am trying to write a RegEx for an input field in Angular / TypeScript that prevents the user from typing anything other than a 1-3 digit number not starting with 0. Restricting the input to only digits is easy, but I am not able to figure out how to restrict an input starting with 0. Everything I try seems to break the RegEx check.
<input matInput
[(ngModel)]="backupIntervalLength"
(ngModelChange)="onIntervalLengthChange($event)"
maxLength="3"
onkeypress="return String.fromCharCode(event.charCode).match(/[^0-9]/g) === null"
>
I'm not familiar with Angular but here is a JS solution, since you didn't tag your question with Angular I assume you can translate it into Angular code.
const input = document.getElementById("input");
input.addEventListener("input", e => {
const { value } = e.currentTarget;
if (!/^[1-9]\d{0,2}$/.test(value)) {
e.currentTarget.value = value.slice(0, -1);
}
});
<input id="input" type="number" />
Turns out it wasn't all that complicated. I just had to think in invert :)
<input matInput
[(ngModel)]="backupIntervalLength"
(ngModelChange)="onIntervalLengthChange($event)"
maxLength="3"
onkeypress="return String.fromCharCode(event.charCode).match(/[^1-9]?[^0-9]?[^0-9]/g) === null"
>
The below works for the most part; however numbers can still be entered via two ways: 'copy paste' and also from browser cache/suggestions, i.e. if your browser is giving you suggestions from your history to fill the input. Numbers can still be achieved in those two ways.
Anyway to eliminate the ability for numbers being entered in the field completely?
<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" />
Check this
abc.oninput = function() {
const val = this
if (/[0-9~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/.test(this.value)) {
const i = this.value.match(/[0-9~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/g)
if (i !== null) {
i.map(function(el) {
val.value = val.value.replace(el, '')
})
}
}
}
<input type="text" data-value-field="value" name="styleName" id="abc" />
onpaste="return false" is used to cancel the paste event.
autocomplete="off" is used to prevent auto-completion.
setInterval(() => { ... }, 100); is used to regularly check the input and remove any numbers or special characters. This prevents the user from being able to use input.value = " ... " in the Developer console to set the input's value to something invalid, as the input will automatically be corrected.
const input = document.getElementById('cleanse');
setInterval(() => {
input.value = input.value.replace(/[^a-zA-Z ]/g, "");
}, 100);
<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" onpaste="return false" autocomplete="off" id="cleanse" />
I have this code in HTML:
<input type="number" step="0.1" class="form-group">
I want the user to be able to enter a 3-digit decimal number like 1.234 but step needs to be 0.1 and it throws an error and prevents the form from submitting.
I've already tried step="0.100" but the result was the same.
I also need to validate other inputs so I can't use no validate in the <form> tag.
What needs to be done?
I'd write a small customized built-in custom element doing just that:
class MyInput extends HTMLInputElement {
constructor(step = 0.1, value = '') {
super();
this.type = 'number';
this.step = this.getAttribute('step') || step;
this.value = this.getAttribute('value') || value;
this.addEventListener('input', (e) => {
this.value = parseFloat(this.value) + 0.034;
})
}
}
customElements.define('my-input', MyInput, { extends: 'input' });
let input = new MyInput(0.1, 1);
document.body.appendChild(input);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />
This definitely needs some tweaking, e.g. if the user types in the input, but this should serve you well as a starting point.
One thought is you could remove the step attribute, disable the +/- slider buttons, and implement your own +/- buttons. Then, when a user clicks those buttons, a JavaScript function is called that retrieves the value in the input area, converts it to a number, and performs the desired step.
You might run into precision issues with using a step like 0.1. In the below snippet I just fixed the number of decimal places to two.
function stepUp(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num + step).toFixed(2);
}
function stepDown(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num - step).toFixed(2);
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<button onclick="stepDown(0.1)">-</button>
<input id="value" type="number" value="0.00">
<button onclick="stepUp(0.1)">+</button>
You can use novalidate and write your own validation in js for other form fields
<form novalidate>
<input type="number" step="0.1" class="form-group" >
<button>submit</button>
</form>
I am trying to add validation for input type number to accept only integer.
I added pattern="\d*" to the element. It works fine for input 10.12, 10.13. But fails for input 10.
I printed the value for the html input. It is 10 instead of 10..
<script>
function getValue(){
alert(document.getElementById("numberInput").value);
}
</script>
<input type="number" id="numberInput"> </input>
<button onclick="getValue();">
Ideally it should consider 10. as invalid input.
Pasting is indeed tricky. I came up with the following:
function setValid(target) {
const val = target.value;
// Remove value, as setting the same value has no effect.
target.value = '';
// Reset value on the next tick
requestAnimationFrame(() => target.value = val);
}
<form action="#" method="post">
Numbers: <input name="num"
type="number"
min="1"
step="1"
onblur="setValid(this)"
onpaste="requestAnimationFrame( () => setValid(this) )"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
<input type="submit">
</form>
What this does is the following:
When the input loses focus, it resets the value
When pasting, it waits until the value is set, and then resets it.
There are probably even better solutions out there.
This answer is based on kneeki's answer here.
my code like this
function Tab(e)
{
var input = e.keyCode ? e.keyCode : e.charCode;
if ((input>=48 && input<=57) || (input==45))
{
if (input==45)
{
//what should i do here? so,
//if user press "-", its auto tab to next textfield,
return false
}
else
return true;
}
else
return false;
}
here my html
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event)">
I've been searching at google. but its return similar article and it's not that I'm looking for.
I have a lot of similar text field, so it is not possible to include the next textfield's name cause of i used array name.
sorry if my english is bad, but i hope you understand what I want
You can focus the next input sibling in this way:
HTML:
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
<input type="text" name="a[]" maxlength='3' onkeypress="return Tab(event, this)">
JS:
function Tab(e, inp)
{
var input = e.keyCode ? e.keyCode : e.charCode;
if ((input>=48 && input<=57) || (input==45))
{
if (input==45)
{
//focus the next input if there is one
while(inp.nextSibling)
{
var inp=inp.nextSibling;
if(inp.nodeType===1 && inp.tagName.toLowerCase()=="input")
{
inp.focus();
break;
}
}
return false
}
else
return true;
}
else
return false;
}
it just takes 10 seconds to ask google. you can't emulate a tab-keypress, but there are different workarounds (maybe you could use an array containing the id's of all you fields, save the index you're at and on pressing dash, focus index+1 in your array (+ setting the saved index onfocus of every text field to note if a user focuses a field by clicking it or really pressing tab))
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you. It does require jquery though.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want - (on the normal keys, I guess) instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use dash instead of plus
// Number 189 found through demo at
// https://api.jquery.com/event.which/
key: 189
});
// Matches all inputs with name "a[]" (needs some character escaping)
$('input[name=a\\[\\]]').plusAsTab();
You can try it out in the PlusAsTab demo, and check out the enter-as-tab demo. If you want to change to the - key, you can call JoelPurra.PlusAsTab.setOptions({key: 189}); from your javascript console.