Javascript Validation on Control-V for the Textbox - javascript

I have to validate the textbox to enter only alpha numeric characters.
The function validateAlphaNumeric(evt, txtbox) fires onkeypress event on textbox.
Below is the function written in Javascript.
But I am not able to get the value of the textbox if I do Ctrl+V. I need to validate if user pastes.
Can any one suggest me on this?
function validateAlphaNumeric(evt, textBox) {
/* File Description : Numbers,Characters,Hyphen(-),Slash(/)and Space */
var charCode;
charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode == 8 || charCode >= 48 && charCode <= 57 || charCode == 45) {
return true;
}
else {
var errorMsg = document.getElementById(textBox.id + 'Error');
if (errorMsg != null) {
errorMsg.innerText = "Please Enter Alpha – Numeric Characters only";
}
return false;
}
}

I have found an answer:
Try this on onpaste event.
Surely will work out.
I tried this:
function onPaste(evt, textBox) {
pastedText = window.clipboardData.getData('Text');
if (pastedText matches regExp) {
return true;
} else {
//display error msg
return false;
}
}
Regards..

validate text box on onblur() event of that TextBox. your problem will sure get solved.

from html5 on there is the oninputevent which does exactly what you want.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput
In the handler, check that the value property of the text box contains only allowed characters.
Note that IE9 has buggy support for this event - basically it doesn't recognize character deletion, but it doesn't affect you because you can't make the text invalid just by removing stuff. See here for more detail:
http://help.dottoro.com/ljhxklln.php
If you can't use oninput because you really need to support IE8-IE7 (hint: you don't really want to) you can instead fix your code by listening to the onpaste event too to get text paste events.

Related

jquery keypress() events are not working for keyup()

Here is the code for keypress function, which is allowing only numbers
http://jsfiddle.net/lesson8/HkEuf/1/
But, for the same keycodes, keyup function is not working. I mean, if I use
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keyup(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)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
The reason for using keyup is to get the current entered value in the textbox. If I use keyup function, I will get the current value. But, If I use keydown or keypress, I am getting the previous or existing value in the textbox
see the updated code with different functions
http://jsfiddle.net/dgireeshraju/HkEuf/7300/
this is the example with keydown, which is giving the existing value.
KeyUp fires after the character inserted only, as you can see your function is actually calling and warning message is displaying.
If you try the same code with KeyDown it will work as the event will be called before a character is inserted
//called when key is pressed in textbox
$("#quantity").keydown(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)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
Key up fires when the user releases a key, after the default action of that key >has been performed.
Keypress fires when an actual character is being inserted in, for >instance, a text input. It repeats while the user keeps the key depressed.
Your code is actaully working in both the cases (you can see the error message atleast ) but since this event are different so is the result. To make it work with keyup you need to empty the input element again since by that time the value has already been entered in input element
$("#quantity").keyup(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)) {
//display error message
$(this).val(''); //<--- this will empty the value in the input.
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
NOTE: However emptying the input does removes the complete value even when there are numbers in it so, I prefer keydown in such cases.
Updated
This is a little hack on input value but (I will still prefer to go with keydown), Use this if you really want keyup to work :). since I am modifying the default browser behaviuor, you might also need to think of lots of other cases here.
$("#quantity").keyup(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)) {
//display error message
if(e.which != 13){ //<--- don't remove when entered is pressed.
$(this).val(e.currentTarget.value.substr(0, e.currentTarget.value.length - 1));
}
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
console.log(e.currentTarget.value);
});
working fiddle

How to use Javascript to filter and ignore keypresses on an input field?

I need to stop accepting input (keystrokes) on an HTML form input field when the length limit has been reached. In straight-up HTML I can do this with maxlength="3" or whatever the length is, but I would like to handle it through Javascript if possible so I can do it together with the next requirement.
I also need to filter the input so that if a field is numeric only numbers can be typed, and if there's a mask or regex any inputs conform to the mask/regex.
Is there a "standard" way to do this in, Javascript, particularly in Dojo 1.9? (I know everybody uses JQuery but we use Dojo because.)
For dojo, if you need any sort of validation, I would use the ValidationTextBox, which takes "maxLength" as a property AND allows for all sorts of nifty validation schemes. The reference for ValidationTextBox is here:
http://dojotoolkit.org/reference-guide/1.9/dijit/form/ValidationTextBox.html
I used pure Javascript because I am not familiar with Dojo, but these event listeners can probably be cleaned up with Dojo.
var input = document.getElementsByTagName('input')[0],
error = document.getElementById('error');
input.addEventListener('keypress', function(e) {
if(e.which < 48 || e.which > 57) {
e.preventDefault();
error.innerHTML = 'Must be a digit';
} else if(e.target.value.length >= 3) {
e.preventDefault();
error.innerHTML = 'Cannot be more than 3 digits';
} else {
error.innerHTML = '';
}
});
We listen to a keypress and then, to make sure it is a digit, we seek that the key pressed was between 48-57 (0-9). If not, then we prevent the key press and show an error. Then we check the input's current length. If it is too long, then prevent the key press and show an error. Otherwise, it worked and we allow the event and clear the error.
You maybe looking for this:
<input id="text" type="text"/>
$('#text').on('keypress',function(e){
var numero = this.value.length;
console.log(this.value.length);
if (e.which != 8 && e.which < 48 || e.which > 57)
{
return false
}
else if (numero === 3 && e.which != 8){
return false //alert user here
}else{
return true // allow backspace only (8)
}
}
);
DEMO

Selecting text on-the-fly from textbox leaves out last character in javascript

I'm trying to get the text from a textbox as a user types, so that I can parse it and display information accordingly as the user enters a command. However, it seems as though the function I'm writing is getting the text from the box before the letter is entered into the text box. How do I prevent the function from grabbing the content from the textbox before the typed character is entered? I considered grabbing the id of the key and altering the inputted string accordingly, but I feel like there should be a better way.
The code:
$('#inputConsoleForm').keydown(function(event){
//Get key code
var code = (event.keyCode ? event.keyCode : event.which);
//Get console text (doesn't behave as expected)
var consoleCommand = document.inputConsoleForm.console.value;
function parseConsoleCommand(consoleCommand) {
/* Returns true if command is valid*/
}
if(code === 13) {
event.preventDefault();
if(!parseConsoleCommand(consoleCommand))
alert("INVALID COMMAND LINE");
else
attemptExecute();//Runs the command
}
if(code === 32 || (code >= 48 && code <= 123) || code === 61 || code === 109 || code === 188 || code === 8) {
if(parseConsoleCommand(consoleCommand)){
$(document.inputConsoleForm.console).css("background-color", "#FFDFDF");
}
else{
$(document.inputConsoleForm.console).css("background-color", "");
}
}
});
You could use the HTML5 input event (falling back to the propertychange event in IE < 9). Here are two answers detailing how to do this:
jQuery keyboard events
Catch only keypresses that change input?
Use "change" for best results I'd say. You could continue to use keydown (or keyup) but you'll have to fetch the key being pressed from the event object and append it to the text string.

Which is the proper way of filtering numeric values for a text field?

I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
html
<input type="text" class="hulk" value="" />
​
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});​
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});

CLEditor - Lose focus if maxlength is reached

I'm trying to recreate a maxlength - function for CLEditor. The objective is:
If a text is entered into a textbox and its longer than the set maxlength, the textbox should lose its focus so that it's not possible, to write any further letters.
What I've achieved so far is that the CLEditor recognizes when the text gets longer than my maxlength.
For losing the focus I've tried a simple return (i.e. return; return false;) and some .blur()-methods (i.e. $(frameDesc).blur(); and cledDesc.$area.blur();).
But those are not working. I'm still able to fill in text even maxlength is reached.
Please have a look at the code:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keypress change', function(){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650){
console.log("Longer than MaxLength");
//lose focus
}else{
//Do something
}
});
Any help and hints would be appreciated :)
Solved this one. That was pretty tricky. The solution (for me) is:
Using the keydown instead of the keypress - event.
So if I'm trying to put in some text in my textbox and maxlength is reached, I'm not able to go on writing. But to be able to delete some text, I need to except the Backspace-key from being rejected too. So I've put in a check, if the pressed key is the backspace-key.
This is what the code looks like now:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keydown change', function(event){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650 && event.which != 8){
console.log("Longer than MaxLength");
//lose focus / stop writing
return false;
}else{
//Do something
}
});
I've added some code to make it work.
I catch even the "canc" key (and others)
Before checking the length of the text I update the textarea, it looks like CLEditor has an internal cache and I had a strange behaviour after deleting and reentering text.
This is working perfectly for me:
var cledDesc = $("#oodsummary").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
var limit = 10;
$(frameDesc).bind('keydown', function(event){
cledDesc.updateTextArea();
var text = cledDesc.$area.val();
if(text.length >= limit &&
event.which != 8 && // back
event.which != 46 && // canc
event.which != 37 && // left
event.which != 38 && // up
event.which != 39 && // right
event.which != 16 && // shift
event.which != 20 && // caps lock
event.which != 91 && // os special
event.which != 18 // alt
) {
alert("Il testo inserito risulta essere troppo lungo.");
cledDesc.$area.val(text.substr(0, limit)).blur();
return false;
}else{
cledDesc.updateTextArea();
return true;
}
});

Categories