Validating user input with JavaScript - javascript

I need to make it so a user can ONLY type a-z0-9 into my input box. How can I make it so the user simply cannot type other characters? If this isn't possible, how can I simply check the input with regex?
Thanks!

Another notable solution is this alphanumeric plugin for jquery:
http://itgroup.com.ph/alphanumeric/
Simple as $('#textField').alphanumeric();

If you use jQuery, there is a format plugin that does exactly what you need. Other than that, you can use onkeyup/onkeyup to call function which will validate input against regex pattern.

You can use the onKeyDown event. If you return false from your event handler, no key press event is fired and the key is "eaten".
Here are the docs from Sun: http://docs.sun.com/source/816-6408-10/handlers.htm#1120313

Here is a solution that's adapted a bit from this page:
window.onload = function () {
document.forms.myForm.myField.onkeypress = keyTest;
}
function keyTest(e)
{
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
reg = /[a-z0-9]/i;
if (key != 8 && key != 9) return reg.test(keychar);
}

Make sure you also perform the validation on the server too (assuming there's a server part to this) in case some users have javascript turned off.

Related

Binding the "onselect" event to a function, that handles the maximum chars. inside an input text field

I am working on a function to limit the number of chars. a user is allowed to type inside an input text field.
This is it:
$.fn.restringLength = function (id, maxLen) {
$(id).keypress(function(e){
var kCode = e.keyCode ? e.keyCode : e.which,
len = $(id).val().length;
if (kCode != 8 && kCode != 46) {
if (len > maxLen) e.preventDefault();
}
});
}
The function binds the keypress event and gets the code of the pushed key.
If the char. limit is reached, it allows only the delete and backspace keys to be pushed.
What it needs to work great, is a way to bind the "onselect" event in order to have the following behavior:
when the user selects the whole text with the mouse, and types a letter or a number, the whole text gets deleted and that letter appears.
This is something that most of us do when we want to replace some text with another, and I'd like my function to enable this.
Any ideas how?
If i may add something,
Your solution use keypress event, so the event is triggered before the new value of input is computed. That's why you have to check for special key like backspace , enter ... theses do not just add a character to the string so they require special treatment.
For this kind of processing, it's more convinient to have the handler triggered after the string computation. In that way, you can access the input value and modify it if it's not correct.
Unfortunately jquery does not support this event but you can use it with vanilla javascript method.
$(id)[0] // get the vanilla js element
.oninput = function(e){
this.value = this.value.substr( 0 , 10 ) // this.value contain the string after the key press processing
}

Keycode is always zero in Chrome for Android

I need to detect the keycode for a custom search box on my website, but the keycode always returns as zero on Chrome for Android (except for backspace, which returns 8). Has anyone else experienced this, and how did you get around it? Our website works on all mobile browsers except Chrome for Android because we can't detect a non-zero keycode or charcode.
I'm running Chrome 27.0.1453.90 on Android 4.1.2 Jelly Bean. The problem can be duplicated with something as simple as:
alert(event.keyCode);
below solution also work for me. might be useful for others also.
var getKeyCode = function (str) {
return str.charCodeAt(str.length - 1);
}
document.getElementById("a").onkeyup = function (e) {
var kCd = e.keyCode || e.which;
if (kCd == 0 || kCd == 229) { //for android chrome keycode fix
kCd = getKeyCode(this.value);
}
alert(kCd)
}
I faced this issue and this is how I figured out how to solve the problem.
First, you need to enable USB debugging onto your Android phone so
you can see the logs of your browser on your desktop machine.
Second, refresh your web app on your phone and inside your console on the desktop type "monitorEvents(document)" or whatever element you want to inspect.
Do the action you want to inspect on your phone.
And this is how I found that the keydown event was actually fired by a unique event called "textInput" which contains the information inside event.originalEvent.data.
Hope this saves you time and good luck!
The true way to get the keyCode is to use
event.which
This property on event object is standardize the event.keyCode property. You can read about it also in jQuery documentation here or in MDN here
In other way, I have a lot of experience with keyboard events on android devices.
Android browser has problems sometimes with keyboard events due to device fragmentation (different ROMs between devices or external keyboard apps). The best way is to try to use all the keyboard events (keydown, keyup and keypress) and compare every result to get the pressed key.
The best way is to use in "input" event and get all the time the last charter. The input event can control like in my answer here.
We encountered this problem recently on a China made Android phone Meizu MX3, which has a deeply customized OS based on Android 4.4.4.
The default browswer and Chrome work just fine, but for some weird reasons we don't know, event.keyCode, event.charCode and event.which return 0 all the time in some other browsers(such as CM Browser or webview of Wechat app).
We resolved this by checking the last character you input such as 'A' or ' '(space), then we convert it to ascii code using charCodeAt such as "A".charCodeAt(0) which returns 97, which is the actual char code we need.
But we can only determine the char code of visible chars using this strategy, which meets our current need thank god.
Hope you guys can get some inspiration from this.
I have faced the same issue with Android Devices of SonyXperia and HTC. I have developing hybrid application where i am validating Amount text field by reading event.keyCode() of the entered char on keydown event from text field, so that i can allow only numbers and dot(.) char to be entered. I tried but it doesn't worked, returning always 0 in these devices.
Later i came with other solution with keyup event and char matching through Regular Expression:
$("#AmountField").keyup(function (e) {
var regex = /^[0-9\.]$/;
var str = $(this).val();
var subStr = str.substr(str.length - 1);
if(!regex.test(subStr)) {
if(str.length >0){
$(this).val(str.substr(0, (str.length - 1)));
}else{
$(this).val();
}
}
});
Hope this can help for the people who facing this issue. Good Luck.
<input type="text" id="char" size="15" onblur="showKeyCode()" value="a">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
<script>
function showKeyCode()
{
var character = document.getElementById ( "char" ).value.substr(this.length - 1);
var code = character.charCodeAt();
var stringall = document.getElementById ( "char" ).value;
var msg = "The Key Code for the \""+character+"\" character is "+code+".";
alert(msg);
}
</script>
For reference
If anybody still digging it.Problem appears on stock Samsung keyboard for
android devices.
Instead use onkeyup.
change the type of the input to tel : <input type="tel">
this will let you log the keyCode but it doesnt log the backspace, and it might force the keyboard on mobile to only numbers.
So in most Android browser if u use keydown or keyup you wont be able to get the data from key or keyCode or which or code
You can use event.data(Inserted data key) and event.inputType(backspace or del in mobile)
In order to achieve the functionality you need you have to apply condition based on user agent for android mobile
if (navigator.userAgent.match(/Android/i)) {
node.addEventListener('input', handleInput, false);
} else {
node.addEventListener('keydown', handleKeyDown, false);
}
const handleKeyDown = event => {
event.preventDefault();
if (!event.key) {
return false;
}
genericFunctionHandleThings(event.key, event.code === 'Backspace');
};
const handleInput = event => {
event.preventDefault(); // Here event.preventDefault doesn't stop user from typing
genericFunctionHandleThings(event.data, event.inputType === 'deleteContentBackward');
node.value = storedOrProcessedValue;
};
Here I have used node.value = storedOrProcessedValue because if we want to make some restriction for user typing we need to process and re assign it to the input
You can use this with Input type text,url,email,tel these I have tested rest I need to check
Need to use charCode instead of keyCode
<input type="text" onKeyPress="return funName(this,event)" />
<script language="javascript">
function funName(th,ev)
{
alert(ev.charCode);
}
</script>

How do I validate entry before input value is set?

I'm having a really strange problem. Here's my current Javascript:
jQuery('.highlightableTDCell input').keydown(function () {
var val = jQuery(this).val();
if (!GridView.prototype.validateStandardCellNumberFormat(val)) {
return false;
}
else return true;
});
When I use this, I can still get away with entering an illegal character, but no more than that. I'm really confused because I thought this would happen first.
Inside of the keydown event, the element.value has not yet been updated to account for the key that is currently being pressed. If you want to stop the key from hitting the input box, you need to interrogate the event.which and see if it is a key you want to allow or not.
The event is raised before the new content entered the input (letting you cancel the default behavior.)
You can use something like this, to get the new content:
$('.highlightableTDCell input').keypress(function(e){
var temp = this.value + String.fromCharCode(e.which)
return GridView.prototype.validateStandardCellNumberFormat(temp)
});
Note that it's not full proof. like when the user entered the new char in the middle of the input.
Validation should be done only on blur. With HTML5 it should be better, but not all browsers support it yet.
Tip: this.value == jQuery(this).val() There is no need to create jQuery object to get the value

Do not allow '&*' pair Textarea in Java Script

While adding text in a textarea, I dont want to allow '*' after '&'.
I want to check on Asterisk keypress, whether previous symbol added is '&', if yes, user cannot add '*'.
Kindly help, how to proceed.
You might be better off having a general function that runs after every "keyup" event which cleans up the textarea by removing any asterisks (*) immediately after an ampersand (&). This way, even if the user pastes some content which contains the invalid sequence (&*) it will still be cleaned up. So something like this:
myTextArea.onkeyup = function() {
myTextArea.value = myTextArea.value.replace(/&\*/, '&');
return true;
};
var input = document.getElementById("input");
input.addEventListener("keydown", function(e) {
if(e.shiftKey && e.keyCode === 55 && input.value.substr(input.value.length - 1) === "*") {
e.preventDefault();
}
},false);
This will add an event to check the incoming character and the last in the current input. If the incoming is shift+55 (thats shift-7 or &) and the last character in the input is "*" preventDefault will bail out of the event and not input what was just typed. This example wont work in IE because its using addEventListener but the same approach will work with IE attachEvent or event jQuery events for full cross browser.
Because you can paste using contextual menu, Ctrl-V, Shift-Ins, etc...
myTextArea.onchange = function() {
myTextArea.value = myTextArea.value.replace(/&\*/, '&');
return true;
};
And of course, this does not replace a good server side validation

how to accept only alphabetical pressed keys ( for "autocomplete" purpose )

am wondering ... how to only accept alphabetical pressed keys from the keyboard .. i am using the jQuery .keypress method ... now i wanna know how to filter the passed key ...
i am trying to build a simple autocomplete plugin for jQuery ...i know a about jQuery UI, but i want to do it myself ...
thanks in advance :)
You can bind a function to the field that replaces anything that's not in the a-z range.
<input name="lorem" class="alphaonly" />
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
$(this).val( $(this).val().replace(/[^a-z]/g,'') );
});
</script>
Source: Allow text box only for letters using jQuery?
In your callback, you can check the event's keyCode property. If you want to disallow the key being entered, simply return false. For example:
$('#element').keypress(function(e)
{
if(e.which < 65 || e.which > 90) //65=a, 90=z
return false;
});
Note that this won't really work very well. The user could still paste in other text, or use a mouse-based entry device, or any number of other things.
I've edited this based on Tim Down's comment and replaced keyCode with which, which is correct across keydown, keyup, and keypress events.
The following will prevent any character typed outside of a-z and A-Z from registering.
$("#your_input_id").keypress(function(e) {
if (!/[a-z]/i.test(String.fromCharCode(e.which))) {
return false;
}
});
This won't prevent pasted or dragged text appearing. The surest way to do that is the change event, which is only fired once the input has lost the focus:
$("#your_input_id").change(function(e) {
this.value = this.value.replace(/[^a-z]+/gi, "");
});
This worked for me, it only accepts letters no special characters or numbers
$("#your-input-here").keypress(function (e) { return validateAlphaKeyPress(e); });
function validateAlphaKeyPress(e) {
if (e.keyCode >= 97 && e.keyCode <= 122) {
return true;
}
return false;
}

Categories

Resources