I would like to disable all symbols entry into an input field that are not associated with following: letters or numbers or spaces or ampersand symbol or full stop.
E.g.
ALLOWED: A-Z, a-z, 0-9, &, ., and space is allowed.
NOT ALLOWED: Every other character e.g. ! # # $ % ^ * ( ) - + = [ ] ; : ' " < > , / ? | = ` ~ etc.
<input id="ItemName" type="text" />
You can register a keypress event handler and return false if you don't "like" the new input :
$('#ItemName').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[A-Za-z0-9&. ]/)) {
return false;
}
});
JSFiddle: http://jsfiddle.net/cgx1yqyf/
Note that this solution requires JQuery
The right way is using an "input" event.
document.addEventListener('input', script);
https://developer.mozilla.org/en-US/docs/Web/Events/input
Question is old, but it's never too late to answer
$(document).ready(function() {
//prevent paste
var usern_paste = document.getElementById('yourid');
usern_paste.onpaste = e => e.preventDefault();
//prevent copy
var usern_drop = document.getElementById('yourid');
usern_drop.ondrop = e => e.preventDefault();
$('#yourid').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
Yes, yes, I know. This question is old. But I'd just give it a try (without jQuery)
HTML
<input type="text" placeholder="Try to put a non-alphabetical character here! (you can put a number and a space too)" id="nochars" />
JS
const input = document.getElementById("nochars"); // gets the element (the input) by it's id
input.addEventListener("input", (event) => {
const char = String.fromCharCode(event.keyCode)); // changes the keycode from a int to a string
if (!(/[a-zA-Z0-9\s\.$]/.test(char))) {
event.preventDefault(); // prevents the default (which is adding the character to the value)
}
});
Also, check on what EventTarget.addEventListener does. (\s is a whitespace - a space)
Related
I have a form in which I want users to only put alphabets, numbers
I want to restrict them from
Using the number as first value Eg. 1abc
Using Capitol letters Eg. 1ABc
Using Spaces Eg. 1 ab CD d5
I only want like abc1 OR a1bc OR f25fhgfh45w
I tried http://jsfiddle.net/m7QrG/506/ but it didn't help me out.
You can use RegExp /^\d|[A-Z\s]+/g to match digit at beginning of string or uppercase letters or space, remove i flag and $ anchor, use input event to also handle user pasting at <input> element
$('.alphaonly').on('input', function() {
$(this).val(function(i, val) {
return val.replace(/^\d|[A-Z\s]+/g, '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
After observing your question and your comments with #guest271314 I came up to with the solution:
$(function() {
var haveFirst = false;
$('.alphaonly').on('keypress', function (event) {
if( $(this).val().length === 0 ) {
haveFirst = false;
}
var regex = new RegExp("^[a-z0-9_]+$");
var first = new RegExp("^[a-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(!first.test(key) && haveFirst == false){
event.preventDefault();
return false;
}else if(regex.test(key)){
haveFirst = true;
}
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
In hoping it will work as you want!
I'm trying to make a jQuery method that would delete wanted chars from selected elements.
For example:
$("input").disallowChars(/\D/g);// should disallow input of all non-digit elements in input elements
This is how I thought to do it, but it doesn't seem to work:
$.fn.disallowChars = function(regexp){
this.keyup(function(){
var value = $(this).val();
value.replace(regexp, "");
$(this).val(value);
});
return this;
};
$("input").disallowChars(/\D/g);
I'm a total newbie at this, how can I make it work.
Thanks
You could use String.fromCharCode() and keypress event instead:
$.fn.disallowChars = function(regexp){
return this.keypress(function(e){
if(String.fromCharCode(e.which).match(regexp)) return false;
});
};
DEMO
BUT doesn't disable any characters to be paste in input using mouse or paste keyboard shortcut.
On modern browsers, you could use input event, or change keyup paste mouseup (ya mouseup, to handle dropped text too):
$.fn.disallowChars = function(regexp){
return this.on('input', function(){
this.value = this.value.replace(regexp, '');
});
};
BUT then once input value is replaced, text carret is put in end (or start depending browser behaviour) of string input.
DEMO
heres a handy routine I use to sanitize some input fields in a current project:
// REPLACE SELECTOR WITH YOUR ID(S) OR SELECTORS...
$('input').bind("change keyup", function() {
var val = $.trim($(this).val());
// READ UP ON REGEX TO UNDERSTAND WHATS GOING ON HERE... ADD CHARACTERS YOU WANT TO ELIMINATE...
var regex = /[":'/\+;<>&\\/\n]/g;
if (val.match(regex)) {
val = val.replace(regex, "");
$(this).val($.trim(val));
}
});
Heres another version I used recently:
$("#myField").on("keypress", function(event) {
// THIS ONLY ALLOWS A-Z, A-Z, 0-9 AND THE # SYMBOL... just change stuffToAllow to suit your needs
var stuffToAllow = /[A-Za-z0-9# ]/g;
var key = String.fromCharCode(event.which);
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || stuffToAllow.test(key)) {
return true;
}
alert( key + ' character not allowed!');
return false;
});
$(document).ready(function() {
$('.expanding').on('keyup',function() {
var textarea = document.getElementsByTagName('textarea')[0];
var submitBtn = document.getElementById('submit-btn');
if(textarea.value == '') {
$('#submit-btn').attr('disabled', true);
} else {
$('#submit-btn').attr('disabled', false);
}
});
});
Here's my code so far. It works fine, but it's missing a feature. So by default, the value of the textarea is an empty string and therefore the button is disabled. However, any whitespace entered enables the button, which I don't want.
Do I use else if? Or an or in the if statement? How do I write this?
Thanks.
You could use trim():
if(textarea.value.trim() == '')
Using the .trim() or $.trim() functions below, strip out the leading & ending whitespaces and then check to see if textarea has a string length (which it won't if it was just a bunch of spaces).
$(document).ready(function() {
$('.expanding').on('keyup',function() {
// Using vanilla javascript
var textarea = document.getElementsByTagName('textarea')[0].trim();
// or with jQuery
var textarea = $.trim(document.getElementsByTagName('textarea')[0]);
var submitBtn = document.getElementById('submit-btn');
if( !textarea.length ) {
$('#submit-btn').attr('disabled', true);
} else {
$('#submit-btn').attr('disabled', false);
}
});
});
Just strip leading and trailing whitespace off the value:
if(textarea.value.replace(/^\s*(.*?)\s*$/, "$1") == '') {
Im using this code to restrict the user to not enter special characters
$("input").keyup(function(){
var text=$(this).val();
$(this).val(text.replace(/[^\w\d\s]/,""));
})
I want to restrict the user to enter only one word without space and also having no numbers and special characters. like this
myword #valid
myword2 #invalid
myword secondword #invalid
$(this).val(text.replace(/[^A-Za-z]/g,''));
Test it here »
here's a jQuery plugin that will prevent typing keys that are not in the specified regex. It also works if you paste something, but that works with replace.
$("body").delegate("[keyfilter]", "keypress", function(event) {
var elem = $(this), filter = elem.attr('keyfilter');
if (event.charCode === 0) {
return;
}
try {
if (!String.fromCharCode(event.charCode).match(new RegExp("[" + filter + "]"))) {
event.preventDefault();
event.stopImmediatePropagation();
}
} catch(e) {}
}).delegate("[keyfilter]", "paste", function(event) {
var elem = $(this), filter = elem.attr('keyfilter');
setTimeout(function() { elem.val(elem.val().match(new RegExp("[" + filter + "]"))[0]) }, 50);
});
the way to use it:
<input type="text" keyfilter="A-Za-z" />
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">