javascript code prevents typing except special characters - javascript

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

Related

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();
// ...

Directive for restricting typing by Regex in AngularJS

I coded an angular directive for inhibiting typing from inputs by specifying a regex. In that directive I indicate a regex that will be used for allow the input data. Conceptually, it works fine, but there are two bugs in this solution:
In the first Plunker example the input must allow only numbers or numbers followed by a dot [.], or numbers followed by a dot followed by numbers with no more than four digits.
If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening. The bug is in the fact I use the expression elem.val() + event.key on my regex validator. I do not know how to get the whole
current value for a input on a keypress event;
The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them.
What changes do I need to make in my code in order to get an effective type restriction by regex?
<html ng-app="app">
<head>
<script data-require="angularjs#1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Restrict typing by RegExp</h1>
PATTERN 1 (^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$) <input type="text" allow-typing="^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$"/><br>
ONLY NUMBERS <input type="text" allow-typing="^[0-9]+$"/><br>
ONLY STRINGS <input type="text" allow-typing="^[a-zA-Z]+$"/>
</body>
</html>
Directive
angular.module('app', []).directive('allowTyping', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
elem.bind('keypress', function(event) {
var input = elem.val() + event.key;
var validator = new RegExp(regex);
if(!validator.test(input)) {
event.preventDefault();
return false;
}
});
}
};
});
If this were my code, I'd change tactics entirely: I would listen for input events instead of trying to micromanage the user interactions with the field.
The approach you are taking, in general, has problems. The biggest one is that keypress won't be emitted for all changes to the field. Notably,
It is not triggered by DELETE and BACKSPACE keys.
Input methods can bypass it. When you entered diacritics as diacritics, your code was not registering the change. In general, if the user is using an input method, there is no guarantee that each new character added to the field will result in a keypress event. It depends on the method the user has chosen.
keypress does not help when the user cuts from the field or pastes into the field.
You could add code to try to handle all the cases above, but it would get complex quick. You've already run into an issue with elem.val() + event.key because the keypress may not always be about a character inserted at the end of the field. The user may have moved the caret so you have to keep track of caret position. One comment suggested listening to keyup but that does not help with input methods or paste/cut events.
In contrast, the input event is generated when the value of the field changes, as the changes occur. All cases above are taken care of. This, for instance, would work:
elem.bind('input', function(event) {
var validator = new RegExp(regex);
elem.css("background-color", !validator.test(elem.val()) ? "red" : null);
});
This is a minimal illustration that you could plop into your fiddle to replace your current event handler. In a real application, I'd give the user a verbose error message rather than just change the color of the field and I'd create validator just once, outside the event handler, but this gives you the idea.
(There's also a change event but you do no want to use that. For text fields, it is generated when the focus leaves the field, which is much too late.)
See Plnkr Fixed as per your approach:
The explanation of why and the changes are explained below.
Side note: I would not implement it this way (use ngModel with $parsers and $formatters, e.g. https://stackoverflow.com/a/15090867/2103767) - implementing that is beyond the scope of your question. However I found a full implementation by regexValidate by Ben Lesh which will fit your problem domain:-
If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening.
because in your code below
var input = elem.val() + event.key;
you are assuming that the event.key is always appended at the end.
So how to get the position of the correct position and validate the the reconstructed string ? You can use an undocumented event.target.selectionStart property. Note even though you are not selecting anything you will have this populated (IE 11 and other browsers). See Plnkr Fixed
The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them.
Fixed the regex - correct one below:
^[0-9]*(?:\.[0-9]{0,4})?$
So the whole thing looks as below
link: function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
elem.bind('keypress', function(event) {
var pos = event.target.selectionStart;
var oldViewValue = elem.val();
var input = newViewValue(oldViewValue, pos, event.key);
console.log(input);
var validator = new RegExp(regex);
if (!validator.test(input)) {
event.preventDefault();
return false;
}
});
function newViewValue(oldViewValue, pos, key) {
if (!oldViewValue) return key;
return [oldViewValue.slice(0, pos), key, oldViewValue.slice(pos)].join('');
}
}
You specified 4 different patterns 3 different pattens in your regex separated by an alteration sign: ^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$ - this will not fulfill the criteria of input must allow only numbers followed by a dot [.], followed by a number with no more than four digits. The bug "where nothing happens" occurs because the variable you are checking against is not what you think it is, check the screenshot on how you can inspect it, and what it is:
Can not reproduce.
You can change the event to keyup, so the test would run after every additional character is added.
It means you need to save the last valid input, so if the user tries to insert a character that'll turn the string invalid, the test will restore the last valid value.
Hence, the updated directive:
angular.module('app', [])
.directive('allowTyping', function() {
return {
restrict : 'A',
link : function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
var lastInputValue = "";
elem.bind('keyup', function(event) {
var input = elem.val();
var validator = new RegExp(regex);
if (!validator.test(input))
// Restore last valid input
elem.val(lastInputValue).trigger('input');
else
// Update last valid input
lastInputValue = input;
});
}
};
});

How to detect brace stroke

I am looking for a general solution to detect braces: { or }.
I have an azety keyboard and I need to use the ALT GR stroke to type them, they are respectively located on the 4 and + keys.
As it is not the same on qwerty keyboard, and probably other dispositions,
I can not know if these characters are being typed just with the information given by the event returned by the keyup listener, I just know that the 4 has been pressed (Chrome does not event let me know that the alt gr is pushed).
Yet, if I use the keypress event, I get the correct code.
But keyup is preferable for me.
var element = document.getElementById('textbox');
element.onkeyup = function(evt){
console.log("keyup");
console.log(evt.which);
};
element.onkeypress = function(evt){
console.log("keypress");
console.log(evt.which);
};
<textarea id="textbox"></textarea>
with that code, I get this output when I type a {:
keypress
123 // { key code
keyup
52 // 4 key code
keyup
225 //alt gr key code
So, is there a solution, independant to the keyboard disposition to detect braces?
AltGr is the same as Ctrl-Alt you could ask for the modifiers while checking.
You must know that the same keyboard could change de configuration of the position of each, keys. I'm have a Spanish/English windows configuration and I change the layout several times in the same day (that changes the position of { and }).
You must use keypress

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
}

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

Categories

Resources