How to specify which characters are allowed in a textbox with jQuery? - javascript

http://jsfiddle.net/WhP8q/
I'm trying to restrict input to alpha numeric, 0-9, A-Z,a-z.
The ASCII table i'm referencing: http://www.asciitable.com/
Here is what I have so far
$(function() {
$("input").bind("keydown paste", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var c = code;
var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
if (code > 32 && !letterAllowed) {
return false;
}
});
});​
right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !##$% all get entered into the text field.
I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk

Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .
I'd recommend something like this:
$("input").on("keypress keyup paste", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});

In case of restrict the character you enter, You can replace the character which is not alphanumberic.
<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
$('#txtNumeric').keyup(function() {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
$('#txtAlphabet').keyup(function() {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, '');
}
});
$('#txtAlphaNumeric').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
});
</script>
Answer taken from: jquery allow only alphanumeric

Turns out, I need to do the following:
$("input").keypress(function(e){
var code = e.charCode;
charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key
see http://api.jquery.com/keypress/

Related

Replace dot and comma while typing and Replace in Inputfield

I would like to disallow the user to type comma or dot while typing in the input field of the type number.
I have already searched and found solution, but it does not work.
If I type e.g. point, no matter which of the two solutions below, the input field is cleared.
This is my input field
<input type="number" class="form-control numbersOnly" name="angebot" id="angebot" min="1" step="1" placeholder="<?php the_field('language_shop_detail_button_counter_offer_placeholder', 'option'); ?>">
Those are the 2 approaches that don't work.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
and
$('.angebotAbgebenContainer #angebot').keyup(function(event) {
var current = $(".angebotAbgebenContainer #angebot").val();
console.log("current", current);
var replaced = current.replace(/\./g, "");
console.log("replaced", replaced);
//replaced = parseInt(replaced);
// $('.angebotAbgebenContainer #angebot').val(replaced);
});
Those are the 2 approaches that don't work. As soon as I make a point, in both approaches, the input field is cleared.
But what I want is, if someone tries to type a point or a comma, it doesn't appear and if someone copy pastes a number, the comma and point must also be gone.
This works for me
Note it is type text
$('#angebot').on("input",function(event) {
var current = $(this).val();
console.log("current", current);
var replaced = current.replace(/[\D\.,]/g, "");
console.log("replaced", replaced);
$(this).val(replaced);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="angebot" />
If you are going to input numeric values in the input only, might as well disable the inputting of all keys except numeric, like:
$(document).on("keypress keyup blur", ".numbersOnly", function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Where 48 - 57 represents keycodes, you can find all keycodes here.
Can use prevent default as below, and on change for paste
$(function() {
$('#angebot').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // 188 for comma, 110 for point
e.preventDefault();
}
}).on('change', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
self.html( self.html().replace(new RegExp('.', 'g'),'') ); // Remove all points
});
})

JS validation allow letters and specific symbol only + change input

I am using a JS solution to allow letters and backspace only.
I want to add more options to the input, but can't see to find the right solution.
My Code:
<input id="inputTextBox">
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
This give me the correct result of only letter input and use of backspace.
For the correct user experiece I need to add the following.
Allow input '?' , '*' and 'spacebar'.
And if possible, change the input in the form when the user typ.
So if a user typ a '?' or 'spacebar', it changes into the value '*' automatic.
Thanks in advance.
Slightly modified from this solution:
How to allow only numeric (0-9) in HTML inputbox using jQuery?
EDIT: added code to preserve position when ? and spaces are replaced
// Restricts input for the set of matched elements to the given inputFilter function.
// Modified to pass element to callback function
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
$(document).ready(function(event) {
$("#inputTextBox").inputFilter(function(el) {
var oldSelectionStart = el.selectionStart;
var oldSelectionEnd = el.selectionEnd;
var oldValue = el.value;
el.value = el.value.replace(/[* ]/g, '?'); //replace * space with ?
el.value = el.value.replace(/[^a-zA-Z?]/g, '');
if (oldValue != el.value)
el.setSelectionRange(oldSelectionStart-(oldValue.length-el.value.length), oldSelectionEnd-(oldValue.length-el.value.length));
return /^[a-zA-Z?]+?$/.test(el.value); // alphabet question only
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
Simply added a keyup function to replace the character '?' and space to *
and also added envent ids of space and '?' in your keypress function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 && inputValue != 63 && inputValue != 42 && inputValue != 32)) {
event.preventDefault();
}
});
$("#inputTextBox").keyup(function(){
var inputTxt = $('#inputTextBox').val();
inputTxt = inputTxt.replace('?', '*').replace(' ', '*')
$('#inputTextBox').val(inputTxt);
});
});
</script>
You have an issue with your code already since the 65 - 123 contains letters, but it also contains [] _ to name a few.
so you probably want 65-90 for A-Z then 97-122 for a-z 48-57 for 0-9. then check each character you want to allow, they probably wont be in a range.
If you look at the ascii chart here https://theasciicode.com.ar/ascii-printable-characters/question-mark-ascii-code-63.html you will see all the numbers you need to include (or exclude)
On the keyUp event, you could look at the value and then change the last character to the * if you wish, but remember that will change the actual value, not just mask it.
If you want it masked, you should use an <input type="password"> field, which has that behaviour by default.

jquery restrict only < and > symbol in textbox

Code:
$j("#<%= txtGradingScale.ClientID%>").bind("keypress", function (e)
{
var keyed = $j(this).val();
$j("#<%= txtGradingScale.ClientID%>").html
(keyed.replace(/\<>/gi, ''));
});
Have to restrict greter than and lesser than symbol in textbox while entering .
above code is not working pls suggest the method .i tried keyCode and Charcode but it's not working
The reason it's not working is because the regular expression /\<>/ (the escape character \ is not needed) is looking for <> and not the characters by themselves, what you want to do is:
$('textarea[name="test"]').keyup(function(e) {
$(this).val($(this).val().replace(/[<>]/ig, ''));
});
This will match any instance of the < and > characters no matter what order they appear in.
You should also use keyup instead of keypress because keypress will only trigger after the next key gets hit, while keyup will trigger whenever the key is released.
Fiddle
You want to test using e.which and compare with corresponding codes for < and >. If you return false or invoke e.preventDefault() when they are encountered, that should do it.
$('#myText').on('keypress', function(e) {
if( e.which === 60 || e.which === 62 ) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="myText" id="myText"/>

Restrict characters in input field

Is there a way to block users from writing specific characters in input fields? I tried the code below, but when a user enters disallowed characters, they appear for a brief period before disappearing. I want the input to remain unchanged when invalid characters are written.
I want to use onchange because other restriction methods do not seem to work on mobile devices. The problem I want to solve is that characters appear briefly before being removed.
function checkInput(ob) {
const invalidChars = /[^0-9]/gi;
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
};
<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
you can use try this,
$('.input').keyup(function () {
if (!this.value.match(/[0-9]/)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
SEE THIS FIDDLE DEMO
Updated :
You can try this Code,
$(document).ready(function() {
$(".input").keydown(function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
SOURCE
SEE UPDATED FIDDLE DEMO
UPDATED FOR ANDROID:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="#+id/textView1"
android:maxLength="1" >
</EditText>
I think it may help you... using android:inputType="number" you can do that.
A combination of keypress and paste events does a trick:
var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;
function checkInput(e) {
var e = e || event;
var char = e.type == 'keypress'
? String.fromCharCode(e.keyCode || e.which)
: (e.clipboardData || window.clipboardData).getData('Text');
if (/[^\d]/gi.test(char)) {
return false;
}
}
<input class="input" maxlength="10" id="text" type="text" autocomplete="off" />
This code prevents from typing or pasting anything but a number. Also no blinking and invalid characters don't show up.
Works in IE7+.
Demo: http://jsfiddle.net/VgtTc/3/
All answers given so far suffer from at least one of the following accessibility issues:
They validate key codes, which does not work with non-QWERTY keyboard layouts.
They do not cover all input methods; especially drag&drop is often forgotten.
They alter the value, which resets the position of the caret.
They use the pattern attribute, but this does not provide feedback until the form is submitted.
Wouldn't it be a much better idea to actually validate the input before it's inserted?
The beforeinput event fires before the input's value is changed. The event has a data property which describes the content that the user wants to add to the input field. In the event handler, you simply check the data attribute, and stop the event chain if it contains disallowed characters.
We end up with the following very simple, very short code.
const input = document.getElementById("input");
const regex = new RegExp("^[0-9]*$");
input.addEventListener("beforeinput", (event) => {
if (event.data != null && !regex.test(event.data))
event.preventDefault();
});
<label for="input">Enter some digits:</label>
<input id="input" />
Some closing notes:
Accessibility: Provide a clear explanation of what input format is expected from the user. For example, you can use the title attribute of the input to show a tooltip explaining the expected format.
Security: This is client-side validation, and does not guarantee that the pattern is enforced when the form is sent to a server. For that, you'll need server-side validation.
Here's a little hack you could try: DEMO
What it does is that it colors every input text white and then changes it back to black if it suits your requirements. If you could live with the bit of lag that occurs when you enter a valid character.
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
else {
document.getElementById('yourinput').style.color = '#000';
}
};
function hideInput(ob) {
document.getElementById('yourinput').style.color = '#FFF';
};
html
<input id="yourinput" class="input" maxlength="1" onKeydown="hideInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
css
input {color:#FFF;}
check this code,
$('.input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
​
<input id="testInput"></input>
<script>
testInput.onchange = testInput.oninput = restrict;
function restrict() {
testInput.value = testInput.value.replace(/[^a-z]/g, "");
}
</script>
I came up with something slightly different. oninput instead of onkeyup/onkeydown, and onchange instead of onpaste.
I restrict invalid characters on both keypress and paste events like:
<input type="text" onkeydown="validateKey(event)" onpaste="validatePaste(this, event)">
And define functions to handle these events inside tab or a separate javascript file:
<script>
function validateKey(e) {
switch(e.keyCode) {
case 8,9,13,37,39:
break;
default:
var regex = /[a-z .'-]/gi;
var key = e.key;
if(!regex.test(key)) {
e.preventDefault();
return false;
}
break;
}
}
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
</script>

Allow text box only for letters using jQuery?

I want to make a text box allow only letters (a-z) using jQuery.
Any examples?
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">
And can be the same to onblur for evil user who like to paste instead of typing ;)
[+] Pretty jQuery code:
<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
Accepted answer
The accepted answer may be short, but it is seriously flawed (see this fiddle):
The cursor moves to the end, no matter what key is pressed.
Non-letters are displayed momentarily, then disappear.
It is problematic on Chrome for Android (see my comment).
A better way
The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});
Note that this allows upper-case and lower-case letters.
I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.
Modify on paste only
Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.
Avoiding autocorrect
Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.
To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.
To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.
Or, alternatively use one of the many input mask plugins out there.
See example.
​$(<selector>).keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});​​​​​
// allow only Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); } // (/[^a-z]/g,''
);
// allow only Number 0 to 9
$('.numberonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^0-9]/,'') ); } // (/[^a-z]/g,''
);
Demonstrated below to allow only letters [a-z] using Jquery:
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
Solution described by #dev-null-dweller is working absolutely.
However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/
So the solution is to use .on() method instead .bind().
If you need to bind existing elements then the code will be :
$('.alphaonly').on('keyup blur', function(){
var node = $(this);
node.val( node.val().replace(/[^a-z]/g,'') );
});
If you need to bind to dynamic elements the code will be :
$(document).on('keyup blur', '.alphaonly', function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') );
});
You need to bind the event to document or some other element that already exist from the document load.
Hope this is helpful for new version of jQuery.
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test"> <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">
Thanks to the first answer.. made this..
<input name="lorem" class="alpha-only">
<script type="text/javascript">
$(function()
{
$('.alpha-only').bind('keyup input',function()
{
if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
}
});
});
</script>
This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..
JQuery function to allow only small and Capital Letters:
Text Field:
<input id="a" type="text" />
JQuery Function:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
Supports backspace:
new RegExp("^[a-zA-Z \b]*$");
This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:
jQuery('.alpha-field, input[name=fname]').mask('Z',{translation: {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});
$("#txtName").keypress(function (e) {
var key = e.keyCode;
if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
e.preventDefault();
}
var text = $(this).val();
$(this).val(text.replace(" ", " "));
});
if (!isValidName(name)) {
//return fail message
} else {
//return success message
}
function isValidName(name) {
var regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(name)) {
return true;
} else {
return false;
}
}

Categories