How to ignore unwanted characters from textbox (JavaScript or jQuery) - javascript

There's a TextBox that I wanna allow users to just enter numbers & not any alphabetical characters.
So how could I ignore those chars entered by end user via JavaScript or jQuery?
Notice I don't wanna replace user's entered value by empty string; Instead wanna ignore case if there is any way for it.

Try that code:
$("#id").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
return false;
}
});
reference http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

You want to attach a handler to the textbox's keypress event. In here check the event.which property to find out what key is pressed, and if it's not a number (between keycodes 48 and 57) return false, which will cancel the default behaviour of typing in the textbox.
$("input").keypress(function (e) {
if (e.which < 48 || e.which > 57)
return false;
});

I would not recommend intercepting keystrokes, allow the user to type whatever he/she wants, and validate on user action (submit/select etc).
Look at this jQuery plugin for instance: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

you said you didn't want to include alphabetical then you said you just want to ignore case? what do you need to do?
You can ignore lower case in JS by using string.toLowerCase()

For numeric-only I use this jQuery extension/plug in
http://www.texotela.co.uk/code/jquery/numeric/

In above options we can prevent the user from keyboard, but what if the user paste something, it will not restrict user to not paste any special character.
For example we are restricting it from keyboard with proper error msg
<script type="text/javascript">
$(function () {
$("#package").keypress(function (e) {
var keyCode = e.keyCode || e.which;
$("#lblError").html("");
//Regex for Valid Characters i.e. Alphabets and Numbers.
var regex = /^[A-Za-z0-9]+$/;
//Validate TextBox value against the Regex.
var isValid = regex.test(String.fromCharCode(keyCode));
if (!isValid) {
$("#lblError").html("Only Alphabets and Numbers allowed.");
}
else
{
$("#lblError").html("");
}
return isValid;
});
});
</script>
Now let's prevent it from pasting special character.
$('#package').bind("paste",function(){
var data= $('#package').val() ;
var removedNotAllowed = data.replace(/[^ws]/gi, '');
$( '#package' ).val(removedNotAllowed);
$("#lblError").html("Only Alphabets and Numbers allowed.");
});

Related

Input allow numbers and only one letter/symbol

I have an input which I want to put a bar code using an scanner (bar code contains only numbers) the problem is that maybe I want to scan a bar code more than once, in this case I want to be able to do something like this:
10*bar code number
Right now I'm able to allow only numbers in my input with this code:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
But with this I'm only able to type numbers, what can I do to allow type a determinate letter/symbol in this case: *
In other words I want a Regex that allows numbers and only this symbol " * ". I tried doing something like this:
if (/\D/g.test(this.value)) this.value = this.value.replace(/^[0-9*]+$/,'')"
But this only allows letters and symbols.
In this cases you should work on char validation and on input value.
The regular expression help validating just the final input, but to do a better job you should avid all not valid input on keyDown event.
And validate the whole input on the keyUp value.
Consider this example:
function onKeyDown(event) {
if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 16 || event.keyCode == 8)
return true;
event.preventDefault();
return false;
}
function onKeyUp(event) {
var value = event.target.value
if (!value.match(/^[0-9]+\*?[0-9]*$/)) {
event.preventDefault();
event.target.value = value.substring(0, value.length-1);
return false;
}
return true;
}
document.getElementById('inputSource').addEventListener('keydown', onKeyDown);
document.getElementById('inputSource').addEventListener('keyup', onKeyUp);
My input sample: <input type="text" value="" id="inputSource"/>

Check if text is selected on keydown event

I have a scenario where i prevent user from entering 2nd numeric after a decimal.I have my code on keydown event.
Below is my code:
$scope.Inputkeydown = function (event, value) {
if (event.keyCode != 8) {
if (value != null && value != undefined && value != "") {
var regex = /^\d*\.\d$/; //this regex passes only decimal numbers with one digit after decimal
if (regex.test(value)) {
event.preventDefault();
}
}
}
};
Now the trouble is if user selects on the text(say 50.0) in the textbox and say presses 5 at that time it is getting prevented too, as in the textbox value is 50.0 and regex allows it go and it is getting prevented from being typed in.
Can i check on keydown if text is being copied?? or is there any other way around?
Instead of preventing the user from entering it, you could just remove it after keypress:
function filterDecimals(inp) {
return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}
Or, if you want to remove everything after it, replace the second \d* with .*
EDIT (example of usage)
This function takes the text as input and returns the new filtered text. To use this, just attach an event handler on keypress like so:
<input type="text" id="filteredbox">
<script>
var txt = document.getElementById("filteredbox");
// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
// sets value of txt to the returned data from filterDecimals()
// if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
if (this.value !== filterDecimals(this.value)) {
this.value = filterDecimals(this.value);
}
});
</script>

How to prevent user from entering decimals?

I've got an order page on my site. Some order items can have decimal quantities, some can't.
What's the best way to prevent the user from entering decimal quantities? (Apart from an alert box and setting the field to zero)?
Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.
Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.
Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:
Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/
$(".integer").keypress(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return(false);
}
});
$(".decimal").keypress(function(e) {
// 46 is a period
if (e.which != 46 && (e.which < 48 || e.which > 57)) {
showAdvice(this, "Decimal numbers only");
return(false);
}
if (e.which == 46 && this.value.indexOf(".") != -1) {
showAdvice(this, "Only one period allowed in decimal numbers");
return(false); // only one decimal allowed
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove();
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500);
}
Here's a little jQuery that prevents non-numerical inputs:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if(currValue.search(/[^0-9]/) != -1)
{
// Change this to something less obnoxious
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
});
});
You can add an event (on key press) and detect if a decimal point has been pressed by the user or not. Also on form submission, use regular expressions to check if the submitted data is correct (because the user can forge the data using live editor like firebug). Also make sure to double check that on your server side in case if user disabled javascript.
for example:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
You better to use the same function cause it's basically the same thing and invoke it from both events.
On server side, check the submitted data again

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