HTML & Javascript: Using a customized Text Input for Password input - javascript

I want to re-invent the password input in HTML.
Okay, here is the work I'd done:
http://www.symplik.com/password.html
(It just a plain html code, nothing really fancy :>)
The "password" is indeed a text input, and I used the onkeyup event to rewrite the input to masking characters.
There're two problems:
(1) backspace or delete cannot be detected
(2) if I type very fast, some characters cannot be captured promptly.
For problem (1). it is partially solved by checking the length of text in the password field and the stored password. Not a very elegant solution anyway.
For problem (2), I'd tried to insert some time delay function in between but still fail. I'd make the field readOnly after every keyUp but it still behaves the same.

Why not use
<input type='password'>
It masks the input for you. No need for javascript.

Related

How to restrict from entering a decimal value in input type number?

So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE
Note: I'm hiding the spin buttons of the input type text. Know more here
EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!
I searched a lot but found nothing.
I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.
Thank You!
Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...
document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>
But you really should not do it! For at least the following reasons:
Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.
I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.
If you have any questions, please ask.
const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
const key = e.key;
const allowed = allowedKeys.includes(key);
if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">

jQuery check if input field characters are highlighted

Background
I have a page that has 3 input elements which takes currency numbers
These input element of type number with jQuery handles which letting up to 2 decimal placing. If user tries to input 3rd decimal, it does not print which is great.
However...
Issue
When input already has valid 2d.p input such as 12.11 and wishes to highlight the field characters (such as click drag highlight to blue) to change/overwrite all, the jQuery handler think that its 3rd decimal input and does not print BUT what it actually needs to do is to overwrite the whole and start from the beginning.
So
Is there a way to check if the input field characters are highlighted?
I know that there is a way around this if my input has type="text" and just use selectionStart and selectionEnd BUT I want to keep it as type="number".
Code: jsfiddle DEMO
Any other suggestion to jQuery code handling 2 decimal place, I would appreciate
If I am understanding your issue correctly, try the following minimal update to detect if the user has 'highlighted' the input value:
if (CharAfterdot > 3 && !window.getSelection().toString()) { return false; }
So if a 'selection' is found via the above method (not empty / undefined) the code allows further input (in your case overriding via highlight).
Updated fiddle:
https://jsfiddle.net/qtr30w05/3/

Keydown event issue on HTML textbox

I have a field that accepts the year, so I have created
input type="number"
and implemented keydown event to restrict user to enter more than 4 digits.
Now I'm facing an issue and need help in figuring out the logic. Following is the case:
Enter 4 digits in the textbox
Select entered text using SHIFT + Arrow Keys
Now if you type a number it should replace the data but since I have barred it, it will not. Need to cover this case.
Also find code in following JSFiddle.
I also have lot of css and validation on input[type=number], so cannot change to input[type=text].
Also same form is used on mobile devices, and when user selects textbox, numeric keyboard should appear.
Edit 1
while searching for option, I found a JSfiddle that could direct us to right direction.
Issue here also is input[type=number] does not support selection property. Reference
As an alternative, we have decided to move to input[type=tel]. This would work in similar fashion, but will allow us to use maxLength attribute. Still if anyone has a better way, please share.
HTML:
<input type="tel" class="year" maxlength="4" data-temp="">
jQuery:
$(document).on('input', '.year', function(){
var txt = $(this).val();
if(isNaN(txt) || txt > 9999){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle
May be this will work , you can use the Regular Express to validate only number and
^[0-9\.\-\/]+$
and also you can use the .length method to insure that you have specific length
You can't submit an invalid value in this case:
<form>
<input type=number min=0 max=9999 required />
<input type=submit value=Submit />
</form>
So I have moved my code to input[type=tel] and Updated JSFiddle
If you check, I have added 2 events
Keydown to restrict from entering any invalid key.
Blur event to check if entered value is number only or not.
Now you might be thinking, if I have already restricted user to enter only number, how can he enter incorrect value.
Explanation
In my implementation, I have used keydown and using keycode, I'm allowing/blocking. Interesting case is when user press and holds shift key. Now on keydown, I get same keycode but value is different(A special character). So checking the integrity on blur.
A better way would have been handling keypress and keydown together and I'll update fiddle and update my answer, but for now I guess this has solved my problem.
Thanks you all for all comments/answer. Also kindly let me know if there are any better ways to implement.

Disable html/javascripts commands in text fields

How do I prevent input in texts fields from containing HTML and JavaScript code?
Example: I have an input text field. If the user enters javascript instructions, then they get executed.
How can I modify
<script>alert('aces')</script>
so that it will show up as normal text in my field and not as a alert when i try to list it?
Have you looked into libraries like underscore.js (used by Backbone.js)?
It comes with escape functions that prevents user entered javascript to run.
http://underscorejs.org/#escape and http://underscorejs.org/#unescape
so you would write:
alert(_.escape(USERINPUT));
this becomes even more important when you add user input to your DOM, for security reasons you need to escape inputs (or allow only a selection of harmless tags like < strong >).

Jquery Validate - Input Mask Conflict

I have a form that uses jquery validate and the form validates on submit and on blur (onfucusout). Some of my fields have masks using the jquery mask plug in. The mask will place something like this in the field (---)---/---- when it comes into focus. When the user clicks out of this field the (---)---/---- disappears. My problem is that although the field is left black it is throwing the validation error thinking that the user has typed in (---)---/---- instead of just leaving it blank.
My first thought was to put a delay on the validate so that it validates after (---)---/---- disappears. My question is how do have set the validate to delay so that it evaluates the field after the characters are gone? If this isn't the right fix can someone help me fix this issue.
Again i think it is caused because the validation is triggering before the mask characters are going away. I need it to validate after the masked place holders disappear. Thanks for any help.
The way I addressed this problem.
Input Mask in my case : "(999) 999-9999"
For my test example i did the following :
(1) The first thing i did was determined what characters were being generated in my DOM.
e.g.
using the below code in FireBug Console.
$('#MyPhoneNumberID').keydown(function(){
console.log($(this).val())
In my case it was spitting out the following (_) -___
(2) The work around I used was to update my regular expression(for phone) and include the mask as part of the regular expression
e.g. "(_) -___" OR correct typed in phone numbers was allowed.
Regular Expression used :
"^(?:+)?(1)?(?:\s*(?:-|.|()?\s*)?(\d{3}|_{3}|\s{3})(?:\s*(?:-|.|))?\s*)?(\d{3}|_{3}|\s{3})(?:\s*(?:-|.)?\s*)?(\d{4}|_{4}|\s{4})$"
Hope this helps!

Categories