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" />
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"
>
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.
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>
I'm trying to prevent the user from pasting unallowed text into an input field. The Input is a randomly generated 8 digit Code, that contains letters and numbers.
But I don't want the user to paste any text that contains other characters.
my input field:
<input type='text' id='form-code-field' name='code' maxlength='8'>
Note:
I'm not looking for something like the readonly attribute, because the user still has to input alphanumeric text into the field.
You could test value input using a regex on input event:
$('#form-code-field').on('input', function(){
if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || "";
else $(this).data('oldValue', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='form-code-field' name='code' maxlength='8'>
For HTML5 browsers you can also do this, and no script required:
<input type='text' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9">
This will not stop someone from write non valid characters, the pattern will be evaluated on submit and will abort the submit with a message if not matched.
Update
I added a plain javascript version for those who don't use jQuery, which works globally on a form. Just set the "pattern" on a input field and it kicks in.
The script also works on input on non HTML5 browsers.
A "safety" note:
As a client side evaluation, this by no means is 100% safe to just store server side, you always need to check whats posted before doing anything with it.
document.getElementById('form').addEventListener('input', function(e){
if (e.target.pattern && e.target.pattern.length > 0) {
var regex = new RegExp(e.target.pattern,"i");
if(!regex.test(e.target.value)) {
if (e.target.value.length > 0) {
e.target.value = e.target.getAttribute('data-old-value') || "";
} else {
e.target.setAttribute('data-old-value', "");
}
} else {
e.target.setAttribute('data-old-value', e.target.value);
}
}
}, false);
<form id="form">
Only alphanum (max 8): <input type='text' id='form-code-field' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9"><br /><br />
Any character (max 5): <input type='text' id='form-code-field' name='code' maxlength='5' ><br />
</form>