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" >
Related
I have looked at this post to help me (regular expression in javascript which allows backspace), but still, I can not use my backspace to delete characters.
I have tried different variations with
(/[0-1,\b]/g)
(/[0-1][\b]/g)
(/[0-1]+[\b]/g)
...nothing is working.
Here is my whole function:
binary.addEventListener('keydown', (event) => {
if (event.key.match(/[0-1]/g)) {
return event;
} else {
event.preventDefault();
}
});
Event handler is attached to <textarea id="binary" placeholder="Binary..." type="text"></textarea>.
I have tried to remove preventDefault(), but my regex does not apply then.
You can check if BACKSPACE is pressed by adding a event.keyCode === 8 || alternative to the if condition.
Also, it is probably "cleaner" to use RegExp.test() to check if a regex matches a string, /[01]/.test(event.key).
let log = document.querySelector('#log'),
test = document.querySelector('#test');
test.addEventListener('keydown', (event) => {
if (event.keyCode === 8 || /[01]/.test(event.key)) {
return event;
} else {
event.preventDefault();
}
});
#test:focus{outline: none;}
<input type='text' id='test' autofocus /><br />
<span id='log'></span>
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'>
I hope this isn't a daft question. I expected google to be promising but I failed today.
I have a textbox <input type="text" id="input1" /> that I only want to accept the input /^\d+(\.\d{1,2})?$/. I want to bind something to the keydown event and ignore invalid keys but charCode isn't robust enough. Is there a good jQuery plugin that does this?
The affect I want to achieve is for some one to type 'hello world! 12.345' and want all characters to be ignored except '12.34' and the textbox to read '12.34'. Hope this is clear.
Thanks.
I don't think you need a plugin to do this; you could easily attach an event and write a simple callback to do it yourself like so:
$('#input1').keyup(function()
{
// If this.value hits a match with your regex, replace the current
// value with a sanitized value
});
try this:
$('#input1').change(function(){
if($(this).data('prevText') == undefined){
$(this).data('prevText', '');
}
if(!isNaN($(this).val())){
$(this).val($(this).data('prevText'))
}
else {
//now do your regex to check the number settings
$(this).data('prevText', $(this).val());
}
})
the isNAN function checks to make sure the value is a number
$('#input1').bind('keyup', function() {
var val = $(this).val();
if(!val)
return;
var match = val.match(/^\d+(\.\d{1,2})?$/);
if(!match)
return;
//replace the value of the box, or do whatever you want to do with it
$(this).val(match[0]);
});
jQuery Keyfilter
Usage:
$('#ggg').keyfilter(/[\dA-F]/);
It also supports some pre-made filters that you can assign as a css class.
You should look at jQuery validation. You can define your own checking methods like this here.
$('input1').keyup(function(){
var val = $(this).val().match(/\d+([.]\d{1,2})?/);
val = val == null || val.length == 0 ? "" : val[0];
$(this).val(val);
});
I found the solution.
Cache the last valid input on keydown event
Rollback to last valid input on keyup event if invalid input detected
Thus:
var cache = {};
$(function() {
$("input[regex]").bind("keydown", function() {
var regex = new RegExp($(this).attr("regex"));
if (regex.test($(this).val())) {
cache[$(this).attr("id")] = $(this).val();
}
});
$("input[regex]").bind("keyup", function() {
var regex = new RegExp($(this).attr("regex"));
if (!regex.test($(this).val())) {
$(this).val(cache[$(this).attr("id")]);
}
});
});
What would be the easiest way to allow only letters/numbers in a textbox. We are using JS/jQuery, but don't want to use a validation plugin?
My solution was this:
jQuery('input[type="text"]').keyup(function() {
var raw_text = jQuery(this).val();
var return_text = raw_text.replace(/[^a-zA-Z0-9 _]/g,'');
jQuery(this).val(return_text);
});
Every time a user tries to enter anything other than a number, letter, space or underscore the function returns a string with the removed banded characters.
You can use a simple regex on form submit to evaluate the contents of the text box, show an error, and stop the form submit. Make a function out of the check and you can also apply it when the text box loses focus. Do this very often and you'll find that you've reimplemented the validation plugin.
$(function() {
$('form').submit( function() {
return validateTB( $('#textbox'), true, $('#textboxError') );
});
$('#textbox').blur( function() {
validateTB( $(this), true, $('#textboxError') );
});
function validateTB(tb,required,msg) {
var $tb = $(tb);
var re = '/^[a-z0-9]';
if (required) {
re += '+';
}
else {
re += '*';
}
re += '$/';
if ($tb.val().match(re) == null) {
$(msg).show();
return false;
}
$(msg).hide();
return true;
}
});
If you don't wanna use plugins - What about some plain old JS validation?
I posted about this on my blog a while ago --> http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html
You'll see that the function in my proposed solution takes a input field ID and a regex (and you'll have to come up with a regEx for your validation needs, should be pretty trivial if you want only aplhanumeric) and sets the background of the control to green or red depending on the outcome of the validation. I know it's not perfect but I think it's enough to get you going, and you can use it as a starting point to roll your own.
I am sure there are mote elegant solutions using jQuery or plain JS but something along these lines has been working pretty well for me so far.
Hope it helps.
A variant on Ian's answer is a little more lightweight and shorter:
function onlyAllowAlphanumeric() {
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g, '');
});
$('input[type="text"]').keyup(onlyAllowAlphanumeric);
Since tvanfossen's snippet triggers only on submit and Ian's is not as pretty as it could be, I just want to add a more cleaner approach:
HTML:
<input id="myinput" type="text">
JS (jquery):
$('#myinput').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This is a simple solution that will check the input on keyup and remove unwanted characters as the user types:
<input class="usr" type="text id="whatever" name="whatever" />
$(".usr").keyup(function() {
var n = $(this).val();
if ( n.match("^[a-zA-Z0-9 ]*$") == null ) {
$(this).val(n.slice(0,-1));
}
});
The regex can be altered to suit specifications.
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">