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

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

Related

javascript code prevents typing except special characters

I was putting together some simple javascript to prevent characters being input in my form. I got to this stage where I was able to prevent all typing, and noticed that it prevents all characters except special ones, like å´ˆø`¨
which I can enter on my mac using: [Option]+`+[Letter key]
How can I prevent these being entered?
HTML:
<form>
<input name="myinput"></input>
</form>
JS:
document.querySelector('input').addEventListener('keypress', function (e) {
e.preventDefault();
return false;
});
fiddle:
https://jsfiddle.net/6qty7dgr/
This is not working because these keystrokes actually start a composition event, i.e the full input has not yet been processed by the IME and you have "half-a-character". So calling preventDefault() on the keydown event here won't prevent the typing of this half character and the browser will insert it in the input anyway.
document.querySelector('input').addEventListener('keypress', function (e) {
e.preventDefault();
});
document.querySelector('input').addEventListener('compositionstart', function (e) {
console.log("composition start fired");
e.preventDefault(); // should have worked per specs, but doesn't...
});
<input name="myinput"></input>
By specs, you should have been able to prevent this by calling preventDefault() on the compositionstart event that does fire. However, no browser actually seems to support cancelling this event and it seems that for technical reasons they won't support it ever. However they should support cancelling the beforeinput event, but as of today only Safari does support cancelling it when it comes from a composition event...
"I was putting together some simple javascript to prevent characters being input in my form."
"How can I prevent these being entered?"
Emphasis added by me
Avoid keyboard events if you are using a form control. Form events usually work better since there is very little variation when interpreting the value of an input as opposed to keyboard events.
In the example below, the <input> listens for the "input" event. As the user types into the <input>, the .value property is being filtered by the following Regexp:
const rgx = new RegExp(/([å´ˆø`¨])*/, 'g');
(...)- Capture group: matched characters that are extracted.
*----- Quantifier: zero or more matches.
[...]- Class: a literal character. -, \, ], and ^ must be escaped by prefixing \ to it.
å´ˆø``¨ are instantly replaced with a zero-space "".
Details are commented in example below
// Bind input tag to the input event
document.forms[0].elements.filter.oninput = dataFilter;
// Pass the Event Object
function dataFilter(e) {
// Delegate to input tag only
if (this.name == 'filter') {
/*
This matches
å´ˆø`¨
*/
const rgx = new RegExp(/([å´ˆø`¨])*/, 'g');
// Replace everything in rgx
const filtered = this.value.replace(rgx, '');
// Assign filtered string as value
this.value = filtered;
}
// Prevent input from rendering everything
e.preventDefault();
};
<form>
<input name='filter'>
</form>
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
https://www.w3schools.com/jsref/event_onkeypress.asp

Characters being injected into input field

I am sure this is something really stupid I am missing.
I am writing a small snippet that adds a hyphen to a string grabbed from an input field. The hyphen is only added once we hit position 4, so I can type 123 and the hyphen will not appear. If I type 1234, it'll automatically change to 1234-. The problem is with handling pasting, somewhere down the line inside jQuery (after my code has executed), it's injecting more characters into the field.
My approach is simple enough. I look at the keyup and keydown event, check the input and insert the hyphen. For pasting I look at the paste even, grab the string, split it and insert a hyphen depending on if one is present or not.
$('[id$="field"]').on('paste', function (event) {
var element = this;
var text = event.originalEvent.clipboardData.getData('text').split('');
if (text.length > 4 && text.indexOf('-') < 0) {
text.splice(4, 0, '-');
$(element).val(text.join(''));
}
});
$('[id$="field"]').bind('keyup keydown', function (event) {
var input = $(this).val();
if (input.length === 4 && event.keyCode !== 8) {
$($(this).val(input + '-'));
}
});
The keyup and keydown listener works just fine. If I paste in 12345, I end up with 1234-5 when I hit $(element).val(text.join('')); yet afterwards that extra char pops whilst jQuery is doing its thing.
I am rather baffled.
Any ideas?
Since you are overriding the typical "paste" behavior by updating the value of the input box directly, you need to prevent the "default" paste behavior.
$('[id$="field"]').on('paste', function (event) {
event.preventDefault();
// ...

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
}

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

onkeyup() event - possible to detect if key press was ignored because a field was at it's maxlength?

I have a form field for entering a user id. The user id is always 6 characters so the field is limited to a maxlength of 6 characters.
The field has an onkeyup() event to call a function that looks up the user id and fills in several other form fields if the user id is valid. Most people I know have used onblur() for something like this but I never liked how a user has to tab to or click on another field before the autofilling AJAX goes off.
The function right now will return w/o doing anything if the field length is < 6 characters or if the key that was pressed is a left or right cursor field.
There's one flaw left I haven't been able to think around. Since the field is limited to 6 characters, if 6 characters are already entered and another key is pressed, the value of the field will not change but the function will fire and validate the field (un-necessary validation/db-query).
Is there anyway to prevent the function from going off in this case? I'm thinking it's not possible but wanted to check. I had a thought if the field length was 6 I could check the last key pressed against the 6th character of the field, but if someone typed something like 'a' as the 6th character and then 'a' again, it wouldn't work. I guess that could eliminate all possibilities except for the one case though one case (not perfect but better).
(rails) <%= f.text_field :uid, :size => 10, :maxlength => 6, :class => 'validate_text', :onkeyup => uid_lookup (event)', :autocomplete => :off %>
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
<script type="text/javascript">
uid_lookup = function(e){
var unicode=e.keyCode? e.keyCode : e.charCode;
if (unicode == 37 || unicode == 39) { // ignore a left or right arrow press
return
}
var uid= $('uid').value;
uid = uid.trim();
$('uid).value = uid; //uid's have no spaces, go ahead and remove if typed
if (uid.length != 6) {
return
}
// db lookup & form autofill
}
</script>
The solution is not to use onkeyup. The correct event to use is HTML5's oninput, which is supported by almost every major browser out there. The one browser lacking support is—of course—Internet Explorer 8, but we can emulate the event using IE's proprietary onpropertychange event which will fire whenever an input element's value property changes.
I'm not familiar with rails, but the best way to apply the event is using JavaScript so that you can gracefully degrade if oninput isn't supported:
var el = document.getElementById("myEl");
// Check support
if ("onpropertychange" in el && !("oninput" in el)) {
el.onpropertychange = function () {
if (event.propertyName == "value")
uuid_lookup.call(this, event);
}
}
else
el.oninput = uuid_lookup;
The other great thing about this event is that it only fires when the value changes - much like onchange but more real-time. This means you can do away with your key detection for left and right arrows in the uuid_lookup function.
Can you not use another variable to store the previous value of the field the last time the validation function was fired? Then you can simply return if uid.value = lastValue.
Not perfect, but it would save some processing.

Categories

Resources