I have this script that only allow numbers to be typed in and everything works great but I want to be able to paste only numbers if the user decides to use paste in an input.
The paste i'm referring to is mouse paste and keyboard paste. Paste in general. I tried to figure this out but I can not seem to find a way to do this.
Here is my code.
//Prevent non numbers from keypress
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
//Prevent non numbers from being pasted only numbers can be pasted
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(){
//???
}
<input type="text" id='numbers-only'>
Here you go.
You can create a list of invalid chars to prevent on keydown i.e. paste.
Below is working code:
var input = document.getElementById("numbers-only");
var invalidChars = [
"-",
"+",
"e",
"."
];
input.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
input.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key) || e.which === 38 || e.which === 40) {
e.preventDefault();
}
});
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<input type="number" id="numbers-only" />
Since it is an input you can easly change che input type to number.
The web browser will then take care of allowing only numbers.
<input type="number" id='phone-number'>
Related
Before you read furtherly, look at my answer and Priyal Pithadiya answer for two different methods on how you can do this.
I have a client that is not satisfied with the solution I got from yesterdays answer on here. Basically I have this script that prevents non number characters from being inserted in an input. It works perfectly when you type but I have a problem here I cannot figure out how to prevent non numbers from being pasted in.
My client has stated that he want to avoid using input number since that was the solution that was offered here but for personal reasons he said he needs to use input text.
If I have to change my code to get a result like this I will.
Please note, I cannot use jQuery, my solution must be javascript only.
This is my code:
//Prevent non numbers from keypress
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
//Prevent non numbers from being pasted only numbers can be pasted
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(){
//???
}
<input type="text" id='numbers-only'>
# try with given solution ,
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
in-line js:
<input type="text" pattern="\d{1,}" onkeyup="this.value = this.value.replace(/[^0-9]/g, '')" />
You can use onpaste Event if you want.
<input type="text" id='numbers-only' onchange="removeChars()">
function removeChars() {
var input = document.getElementById('numbers-only');
input.value = input.value.replace(/[^0-9]/g, '');
}
Thanks Priyal Pithadiya for your help I will like to post two versions of Priyal Pithadiya examples from earlier and now which includes two versions one is with
a onpaste example and the other one is based on using an addEventListener by paste this is for any future readers reading this. All credit goes to Priyal Pithadiya.
With onpaste
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
function myFunction(e) {
var el = e;
setTimeout(function() {
el.value = el.value.replace(/\D/g, '');
}, 0);
}
<input type="text" id="numbers-only" onpaste="myFunction(this);" >
With a event listener
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
I am using
document.getElementById('input-field').addEventListener('keyup', function (e) {
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
});
It almost works. The problem is that I cannot use key arrows, backspace, delete, ctrl+a, etc.
How can I limit it to only those keys that will give a string representation in the specific input?
To ignore those keys you need to add a condition before validating your input.
For example you can make an array containing the list of all KeyCodes that you want to ignore and just test if the typed key isn't one of them.
Here's what you need:
document.getElementById('input-field').addEventListener('keypress', function(e) {
//An array of special Keys
var specialKeys = [37, 38, 39, 40, 8, 13, 27, 46];
if (specialKeys.indexOf(e.which) === -1) {
console.log(String.fromCharCode(e.which)+ ' Key is validated!');
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
Note:
As mentioned in comments you need to use keypressevent instead of keyup to validate every inputted character immediately.
Well there is somehow to limit your input range. But I think in this case you are looking for a way to identify only printable key events.
You can achieve this by using the solution proposed by #TimDown on How to detect if the pressed key will produce a character inside an <input> text-box? applied to a keypress event as you can see on the code below. So then, you can work just with printable key events.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
document.getElementById('input-field').addEventListener('keypress', function (e) {
if(isCharacterKeyPress(e)){
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
e.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
problem
i was implementing user cannot enter special character in textbox.
script is working on ie, safari, chrome but mozilla treating as special character.
what i need
i need backspace so that user can edit textbox values.
html code
<input type="text" id="school" name="school"/>
js code
$("#school").bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
console.log(key);console.log(flag);
if (!regex.test(key) && flag=="false") {
console.log("if");
//jQuery("#errmsg").html(localStorage.getItem("datas")).show();
event.preventDefault();
return false;
}
else
{
console.log("else");
}
//alert(data);
});
js fiddle link : http://jsfiddle.net/HGJb3/295/
any help is most appericiated.
i came up with solution : http://jsfiddle.net/HGJb3/297/ now it works
I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).
I was able to find the solution for this in c# / .net but not for regular web html. If there's already an answer let me know and i'll close question.
How to create a text box that only will allow certain characters (ex. alphanumeric) based on a given regex (ex. [a-zA-Z0-9])? So if a user tries to enter anything else, paste included, it is removed or not allowed.
<input type="text" class="alphanumericOnly">
The basic function would be this:
string = string.replace(/[^a-zA-Z0-9]/g, '')
This would replace any character that is not described by [a-zA-Z0-9].
Now you could either put it directly into your element declaration:
<input type="text" class="alphanumericOnly" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')">
Or (as you used the class hint) you assign this behavior to every input element with the class alphanumericOnly:
var inputElems = document.getElemenstByTagName("input");
for (var i=0; i<inputElems.length; i++) {
var elem = inputElems[i];
if (elem.nodeName == "INPUT" && /(?:^|\s+)alphanumericOnly(?:\s+|$)/.test(elem.className) {
elem.onkeyup = function() {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
}
}
But it’s probably easier to do that with jQuery or another JavaScript framework:
$("input.alphanumericOnly").bind("keyup", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
Example on how to allow alphanumeric chars and space (a-z, A-Z, 0-9 and space, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-zA-Z0-9 ]/g)){this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');}});
Eample on how to allow only lowercase alpha chars (a-z, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-z]/g)){this.value = this.value.replace(/[^a-z]/g, '');}});
etc...
Assuming you have the input stored as the variable input...
input.onkeyup(function(e) {
this.value = this.value.replace(/\W/g, '');
}
After every keypress the value of the input will be stripped of any non-alphanumeric characters.
If you use a .replace method on the keyup event the input will flicker with the non-alphanumeric characters as they're typed, which appears sloppy and doesn't comply with OCD folks like myself.
A cleaner approach would be to bind to the keypress event and deny the characters before they even arrive at the input, like the following:
$('.alphanumericOnly').keypress(function(e){
var key = e.which;
return ((key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 95 && key <= 122));
});
A list of basic keycodes can be found here if this particular set doesn't suit your specific needs.
I've noticed that at least in my case, with the paste and drop events, replacing the text wasn't working because at that point the value property of the input was still the previous one. So I did this:
With pure javascript:
function filterInputs() {
var that = this;
setTimeout(function() {
that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
}, 0);
}
var input = document.getElementById('theInput');
input.addEventListener('keyup', filterInputs);
input.addEventListener('paste', filterInputs);
input.addEventListener('drop', filterInputs);
input.addEventListener('change', filterInputs);
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">
With jQuery:
function filterInputs() {
var that = this;
setTimeout(function() {
that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
}, 0);
}
$('#theInput').on('keyup paste drop change', filterInputs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">