jQuery method that disallows input of certain chars - javascript

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;
});

Related

Restricting users from inserting spaces, capitol letters, first value as int in textbox using jquery

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!

How to replace (copy paste) non alpha characters in the textbox

My requirement is like I need to replace non alpha characters in the text box i achieved it only if the user types in the text box, but if the user copy paste some values like this
"asd5653tYgh45Ghgs34gthth65TGhd"
the values are not replaced as expected . Here 65 is not replaced, to replace it I need to do keyup or keypress again, after that only the value is replaced. I've attached the jsfiddle link for your reference.
Code:
Html:
Name :<input type='text' id='txtName' />
jQuery:
$("#txtName").on('keyup keypress',function(){
var pattern = /^[a-zA-Z]+$/;
var txtval = $("#txtName").val();
if(!pattern.test(txtval)){
$(this).val($(this).val().replace(/[^a-zA-Z]+/,''))
}
});
Link:
Demo Fiddle
here is your solution: http://jsfiddle.net/9knXh/9/
the new pregmatch is /[^a-zA-Z]+/g the g at the end means do all except for only 1
so the new code:
$(this).val($(this).val().replace(/[^a-zA-Z]+/g,''))
EDIT: i also added change for the people who use the right mouse paste
use g at end to resolve your issue
http://jsfiddle.net/9knXh/7/
$("#txtName").on('keyup keypress',function(){
var pattern = /^[a-zA-Z]+$/;
var txtval = $("#txtName").val();
if(!pattern.test(txtval)){
$(this).val($(this).val().replace(/[^a-zA-Z]+/g,''))
}
});
Use this code:
$("#txtName").on('keydown', (function() {
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
if ('v' == String.fromCharCode(keyCode).toLowerCase()) {
`enter code here`
}
}
return true;
});

Disable spaces in Input, AND allow back arrow?

I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?
$(function() {
var txt = $("input#UserName");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
fiddle: http://jsfiddle.net/EJFbt/
You may add keydown handler and prevent default action for space key (i.e. 32):
$("input#UserName").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
DEMO: http://jsfiddle.net/EJFbt/1/
This seems to work for me:
<input type="text" onkeypress="return event.charCode != 32">
It doesn't "disable" the back arrow — your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.
Simply don't do that.
Use a better mechanism for banning spaces, such as returning false from an onkeydown handler when the key pressed is space:
$(function() {
$("input#Username").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
});
This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.
Update
#VisioN's adapted code will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyup handlers that affect your textbox value whilst your caret is still active within it.
So here's the final code:
$(function() {
// "Ban" spaces in username field
$("input#Username").on({
// When a new character was typed in
keydown: function(e) {
// 32 - ASCII for Space;
// `return false` cancels the keypress
if (e.which === 32)
return false;
},
// When spaces managed to "sneak in" via copy/paste
change: function() {
// Regex-remove all spaces in the final value
this.value = this.value.replace(/\s/g, "");
}
// Notice: value replacement only in events
// that already involve the textbox losing
// losing focus, else caret position gets
// mangled.
});​​​​​
});
Try checking for the proper key code in your function:
$(function(){
var txt = $("input#UserName");
var func = function(e) {
if(e.keyCode === 32){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
That way only the keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.
If you're unsure about a certain keyCode try this helpful site.
One liner:
onkeypress="return event.which != 32"

How to REALLY limit the available character for an input field using jQuery?

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).

Javascript Regex Only Textbox

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">

Categories

Resources