Disable pasting text into HTML form - javascript

Is there a way using JavaScript to disable the ability to paste text into a text field on an HTML form?
E.g.
I have a simple registration form where the user is required to input their email twice. The second email entry is to verify there are no typos in the first email entry. However if the user copy/pastes their email then that defeats the purpose and I've been experiencing users having problems because they've input the wrong email and copy/pasted it.
Maybe I wasn't clear on my question but I am not trying to prevent people from copying (or drag selecting) text on their browser. I just want to stop them from pasting input into a text field to minimize user error.
Perhaps instead of using this "hack" you can suggest another solution to the core problem of what I'm trying to solve here? I've done less than half a dozen user tests and this has already happened twice. My audience does not have a high level of computer proficiency.

Don't do it. Don't mess with the user's browser. By Copy + Pasting into an E-Mail confirmation field, the user accepts responsibility over what they type. If they are dumb enough to copy + paste a faulty address (it has happened to me) then it's their own damn fault.
If you want to make sure that the E-Mail confirmation works out, have the user check their E-Mail while your site waits ("Please open your webmail program in a new window"). Show the E-Mail address in big fat letters ("The confirmation E-Mail was sent to.... made an error? CLick here to change).
Even better, if you can, let the user have some kind of limited access without confirming. That way, they can log in straight away and you improve your chances to keep in touch with the visitor even if the confirmation mail is blocked due to other reasons (e.g. spam filters).

Add a class of 'disablecopypaste' to the inputs you want to disable the copy paste functionality on and add this jQuery script
$(document).ready(function () {
$('input.disablecopypaste').bind('copy paste', function (e) {
e.preventDefault();
});
});

I recently had to begrudgingly disable pasting in a form element. To do so, I wrote a cross-browser* implementation of Internet Explorer's (and others') onpaste event handler. My solution had to be independent of any third-party JavaScript libraries.
Here's what I came up with. It doesn't completely disable pasting (the user can paste a single character at a time, for example), but it meets my needs and avoids having to deal with keyCodes, etc.
// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
To make use of this in order to disable pasting:
<input type="text" onpaste="return false;" />
* I know oninput isn't part of the W3C DOM spec, but all of the browsers I've tested this code with—Chrome 2, Safari 4, Firefox 3, Opera 10, IE6, IE7—support either oninput or onpaste. Out of all these browsers, only Opera doesn't support onpaste, but it does support oninput.
Note: This won't work on a console or other system that uses an on-screen keyboard (assuming the on-screen keyboard doesn't send keys to the browser when each key is selected). If it's possible your page/app could be used by someone with an on-screen keyboard and Opera (e.g.: Nintendo Wii, some mobile phones), don't use this script unless you've tested to make sure the on-screen keyboard sends keys to the browser after each key selection.

Just got this, we can achieve it using onpaste:"return false", thanks to: http://sumtips.com/2011/11/prevent-copy-cut-paste-text-field.html
We have various other options available as listed below.
<input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/><br>

You can..... but don't.
You should not be altering the default behaviour of a users browser. It really is bad usability for your web application. Also if a user wants to disable this hack then they can just disable javascript on their browser.
Just add these attributes to the textbox
ondragstart=”return false” onselectstart=”return false”

Crazy idea: Require the user to send you an email as part of the signup process. This would obviously be inconvenient when clicking on a mailto link doesn't work (if they're using webmail, for example), but I see it as a way to simultaneously guarantee against typos and confirm the email address.
It would go like this: They fill out most of the form, entering their name, password, and whatnot. When they push submit, they're actually clicking a link to send mail to your server. You've already saved their other information, so the message just includes a token saying which account this is for.

You can use jquery
HTML file
<input id="email" name="email">
jquery code
$('#email').bind('copy paste', function (e) {
e.preventDefault();
});

How about sending a confirmation email to the email address that the user has just entered twice in which there is a link to a confirmation URL on your site, then you know that they have got the message?
Anyone that doesn't click to confirm the receipt of the email may have entered their email address incorrectly.
Not a perfect solution, but just some ideas.

Extending #boycs answer, I would recommend also using "on".
$('body').on('copy paste', 'input', function (e) { e.preventDefault(); });

Functional approach with VanillaJS
function pasteNotAllowFunc(xid){
let myInput = document.getElementById(xid);
myInput.onpaste = (e) => e.preventDefault();
}
function copyNotAllowFunc(xid){
let myInput = document.getElementById(xid);
myInput.oncopy = (e) => e.preventDefault();
}
copyNotAllowFunc('copyInput')
pasteNotAllowFunc('pasteInput')
Copy
<input id="copyInput" value="copy not allow" />
<hr/>
Paste
<input id="pasteInput" value="paste not allow"/>
<hr/>
Textarea
<textarea id="test" value="Paste here"></textarea>

if you have to use 2 email fields and are concerned about the user incorrectly pasting the same mistyped email from field 1 to field 2 then i'd say show an alert (or something more subtle) if the user pastes something into the second email field
document.querySelector('input.email-confirm').onpaste = function(e) {
alert('Are you sure the email you\'ve entered is correct?');
}
this way you don't disable paste, you just give them a friendly reminder to check what they've presumably typed in the first field and then pasted to the second field is correct.
however, perhaps a single email field with autocomplete on is all that's needed. chances are they've filled their email in correctly before on another site at some point and the browser will suggest to fill the field with that email
<input type="email" name="email" required autocomplete="email">

You could attach a "keydown" listener to the input box to detect whether or not the Ctrl + V keys are being pressed and, if so, stop the event or set the input box's value to ''.
That wouldn't handle right clicking and pasting or pasting from the Edit menu of the browser, though. You may need to add a "last length" counter to the keydown listener and use an interval to check the field's current length to see if it increase since the last keystroke.
Neither is recommended, though. Form fields with paste disabled are extremely frustrating. I'm capable of typing my email correctly the first time, so I reserve the right to paste it into the second box.

Add a second step to your registration process. First page as usual, but on reload, display a second page and ask the email again. If it's that important, the user can handle it.

Simple solution: just reverse the registration process: instead of requiring confirmation at the end of registration process, request confirmation at the beginning of it! I.e. the registration process started with a simple form asking for e-mail address and nothing else. Upon submitting, an e-mail with link to a confirmation page unique to the e-mail address sent out. The user go to that page, then the rest of information for the registration (user name, full name, etc.) will be requested.
This is simple since the website does not even need to store anything before confirmation, the e-mail address can be encrypted with a key and attached as part of the confirmation page address.

from
Some may suggest using Javascript to capture the users' actions, like right-clicking the mouse or the Ctrl+C / Ctrl+V key combinations and then stopping the operation. But this is obviously not the best or simplest solution.
The solution is integrated in the input field properties itself together with some event capturing using Javascript.
In order to disabled the browsers' autocomplete, simply add the attribute to the input field. It should look something like this:
<input type="text" autocomplete="off">
And if you want to deny Copy and Paste for that field, simply add the Javascript event capturing calls oncopy, onpaste, and oncut and make them return false, like so:
<input type="text" oncopy="return false;" onpaste="return false;" oncut="return false;">
The next step is using onselectstart to deny the input field's content selection from the user, but be warned: this only works for Internet Explorer. The rest of the above work great on all the major browsers: Internet Explorer, Mozilla Firefox, Apple Safari (on Windows OS, at least) and Google Chrome.

Check validity of the MX record of the host of the given email. This can eliminate errors to the right of the # sign.
You could do this with an AJAX call before submit and/or server side after the form is submitted.

Using jquery, you can avoid copy paste and cut using this
$('.textboxClass').on('copy paste cut', function(e) {
e.preventDefault();
});

I use this vanilla JS solution:
const element = document.getElementById('textfield')
element.addEventListener('paste', e => e.preventDefault())

With Jquery you can do this with one simple codeline.
HTML:
<input id="email" name="email">
Code:
$(email).on('paste', false);
JSfiddle: https://jsfiddle.net/ZjR9P/2/

You can disable the copy paste option with jQuery by the below script:
jQuery("input").attr("onpaste","return false;");
of by using the bellow oppaste attribute into the input fields.
onpaste="return false;"

what about using CSS on UIWebView? something like
<style type="text/css">
<!—-
* {
-webkit-user-select: none;
}
-->
</style>
also you can read detail about block copy-paste using CSS
http://rakaz.nl/2009/09/iphone-webapps-101-getting-safari-out-of-the-way.html

I did something similar to this for http://bookmarkchamp.com - there I wanted to detect when a user copied something into an HTML field. The implementation I came up with was to check the field constantly to see if at any time there was suddenly a whole lot of text in there.
In other words: if once milisecond ago there was no text, and now there are more than 5 chars... then the user probably pasted something in the field.
If you want to see this working in Bookmarkchamp (you need to be registered), paste a URL into the URL field (or drag and drop a URL in there).

The way that I would resolve the issue of confirming an email address is as follows:
Before going through the main process - say registering the user - first ask them to enter their email address.
Generate a unique code and send it to that email address.
If user has entered the correct email address, they will get the code.
User must enter that code along with their email address, and their other required information, so they can complete the registration. - Please note that if this time they enter a wrong email address (or a wrong code), because it will not match with the code, the registration will not go through, and the user will be informed right away.
If the email address, the code, and other registration information have been entered correctly, the registration is complete and user can start using the system immediately. - no need to to respond to any other email address in order to activate their account
For better security, the code should have a limited lifetime, and it should be allowed only once in the registration process.
Also, in order to prevent any malicious robot applications, it is better to accompany the first step with captcha or a similar mechanism.

if you are using angular
<input type="number" (keydown)="refuseInvalid($event) (input)="refuseInvalid($event)" (paste)="refuseInvalid($event)"> </input>
then in your javascript or typescript
refuseInvalid(event) {
if (event.type == 'input' || event.type == 'paste') {
event.preventDefault()
return false;
}
if (["-", "+", "e", "."].includes(event.key)) {
event.preventDefault();
return false
}
}
Please note the use of ".". It will disallow decimal point numbers too.

Hope below code will work :
<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>

Related

How would I save input from a text box and then move to the next page? (Javascript/HTML)

As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.

Block submitting the order without filled all inputs?

is there a way how can I warn the user when he clicks the submit button (which has its action PHP in different file) that he didn't fill all inputs (instead of submitting empty field) and make him stay on that page and correct it (althought the action php is in different file)? Thank you
No JavaScript necessary! Just use the HTML5 required attribute:
<input type="text" name="username" placeholder="Enter your username" required />
Obviously, you're going to have to validate it server-side as well, since the user can change this code using Inspect Element of Firebug. But that's easy enough:
<?php
if (isset($_POST['username') && $_POST['username'] != '') {
// Passed
} else {
// Failed
}
Try this javascript code
<SCRIPT>
function sub()
{
var usrname=document.getElementById("username").value;
usrname=usrname.replace(/ /g,""); //for checking user isnt just entering spaces
if(usrname!="")
{
document.getElementById("frm").submit();
}
}
</SCRIPT>
http://jsfiddle.net/RhLyE/3/
Yes, you can handle the onsubmit event of the form. see here. Your php action script could still receive invalid data if the browser has javascript deactivated though.

JavaScript - Forcing redirect if default value is changed in text field on a form

I have a form that is dynamically pre-filled with values which on submission does an API call to update a 3rd party database. I'm fairly new to JS, but I have a problem whereby if a colleague sends the form around to others, it'll do an API call to update their contact record and not create a new contact record for anyone that changes the email field.
Is there a way to force a re-direct to a static form URL if someone starts to change the email field? I was looking at something like:
document.getElementById('email').onchange=function()
{
if (this.value != this.defaultValue)
location.href='http://valueinhere'
}
I could always trigger a message to popup that explains why the redirect to the static form if need be?
You can use this:
HTML
<input type="text" id="email" value="email.com" firstvalue="email.com" />
JS
document.getElementById('email').onkeyup = function () {
var firstvalue = this.getAttribute('firstvalue');
if (this.value != firstvalue) {
alert('You will be rediretioned!');
window.location.href = 'http: //www.valueinhere.com';
}
};
DEMO HERE
I used the onkeyup event instead because the onchange triggers only on blur, so if they change the mail but not click in another input/element nothing will happen.
Keep in mind that changing what would be the expected behavior if a web page is not user friendly. Maybe better with a disabled input field and a button "change" just beside it.
In that case you can use this:
HTML
<input type="text" id="email" value="email.com" disabled="disabled" />
<button type="button" id="mailchange">Change this</button>
JS
document.getElementById('mailchange').onclick = function () {
alert('You will be rediretioned!');
window.location.href = 'http: //www.valueinhere.com';
};
DEMO HERE
in JS, the 'onchange' triggers when the input value is finished changing (i.e, in text input - upon blur). You should maybe want to try using the 'onkeydown' and 'onmouseup' (for copy and paste) events to check the difference between the old value and the current one.

Using jQuery validate plugin: onfocusout, onkeyup notworking as expected on production site

I am using jQuery Validate plugin v.1.9.0 it works very nicely. But I am facing this issue, once the user submits the form & if there are any errors, it correctly display error message. The problem is that it does not update the message if the user takes an action to remedy that error. E.g. if a field is required, upon getting the message the first time, user starts typing, then that message should go away.
In the docs it mentions that onfocusout & onkeyup are used for this purpose & by default they are set to true. The funny thing is it seems to work on my local workstation but it fails (silently) once I upload my code to production site. I thought I was messing it up royally somehow so I fired up jsfiddle and put relevant code to see if it happens there as well.
I was amazed to see it happens there as well. So my question is why does it work on my local machine but not on production sites?
P.S. Self-contained example at http://jsfiddle.net/tankchintan/cge44/5/
UPDATE
To replicate the issue, do -
Go to the jsfiddle page.
Without filling out any fields hit submit the form.
It will show error message besides each field.
Now start typing in any one of the fields.
You will notice that the error message doesnt go away, even though the rule is satisfied. On my local machine that error mesaage does go away, once I type anything in the field.
Use this instead!
onkeyup: function(element) { $(element).valid(); },
onfocusout: function(element) { $(element).valid(); },
This problem even exists in some of the examples on the JQuery website.
I found that the problem occurs when the input element has no type. Web browsers assume that the type is "text" if not specified, but jquery.validate has a problem with that. Your input element should look like this:
<input id="cname" name="name" type="text" class="required" minlength="2" />
Apparently this doesn't work if your jQuery library is too new. I was experiencing the same thing, rolling back from jquery v1.7.2 to v1.3.2 fixed the problem.
The example page at http://jquery.bassistance.de/validate/demo/ uses 1.3.2, but I'm not sure which specific version of jquery this breakage occurred in.
The following works for me:
$(document).ready(function () {
$("#myFormElement").submit(function (event) {
var validator = $.data($('form')[0], 'validator');
validator.settings.onfocusout = function (element) { $(element).valid(); };
validator.settings.onkeyup = function (element) { $(element).valid(); };
});
var validator = $.data($('form')[0], 'validator');
validator.settings.onfocusout = false;
validator.settings.onkeyup = false;
});
This disables initial onkeyup validation. If the user then clicks submit, we re-enable validation so that once the field is valid, he/she is given immediate feedback.
I'm not sure why these properties are boolean initially and then callbacks on the submit event. I only found the method by setting the properties to true in the submit event, which caused an exception in the validation library (was attempting the call function).
I think the default behaviour is to only hide that message when the field validates e.g. 'Please enter a valid email address' disappears after you enter 'foo#example.com', which I think makes sense.
See demos: http://jquery.bassistance.de/validate/demo/
I think you might be trying to do something similar to this: jquery validate: focusCleanup: true and focusInvalid: false don't work as expected

JavaScript log-in validation by-passed by IE8

I have a log-in web page that uses JavaScript for name and password validation. It works fine in Mozilla Firefox, but IE8 allows logging in without entering name and or password. It posts a script-restriction warning which, when you click on it, you can chose to enable the JavaScript. That's fine except you can just bypass that step by clicking the Log In button on the web page and you're in. That's a big problem. So it's not running the JavaScript. That defeats the whole purpose of the page.
This (xhtml) form tag calls the JavaScript:
form name="form1" action="TestAccess.htm" onsubmit="return butCheck_onclick()"
This input tag contains the log-in button:
input type="submit" class="center" value="Log In"
I need some kind of work-around so that I can fool IE into either running the JavaScript before loading the next page or some way of stopping the HTML from allowing the next page to load before it runs the JavaScript. But then why would I need the JavaScript if I could implement such restrictions in HTML? I hope I'm making sense. Thanks for any help you can give. ---Andy V.
Here's the JavaScript function I have:
<script language="javascript">
var global="";
function butCheck_onclick()
{
var password = document.form1.password.value;
var Name = document.form1.memName.value;
/*if(Name=="")
{
alert("Enter User name and password.");
} */
var swFound= "NF";
var valName= new Array();
valName[0]= "Roland";
valName[1]= "Korg";
valName[2]= "Peavy";
var valpassword= new Array();
valpassword[0]= "123";
valpassword[1]= "456";
valpassword[2]= "789";
for(var loop=0; loop < valName.length; loop++)
{
if(Name==valName[loop])
{
swFound="F";
if(Name!=valName[loop])
{
swFound="NF";
}
if(password!=valpassword[loop])
{
alert("Invalid password. Please enter a valid password.")
document.form1.password.focus();
document.form1.password.select();
return false;
}
}
}
if (swFound!="F")
{
alert("Invalid last name entry. Please enter a valid last name.")
document.form1.memName.focus();
document.form1.memName.select();
return false;
}
}
</script>
You should never do authentication on the client side. Always do your username/password check on the server side.
In your code, for example, all I would have to do is view the source of the page and copy/paste the username and password.
or even just copy paste the destination url.
Furthermore, simply disabling javascript would clearly be enough.
The only validation you might do on the clientside is determining (at registration time) if the entered values are of the right length, etc. (and duplicated on the server side)
EDIT:
see The definitive guide to form-based website authentication for some good advice from SO users on website authentication.
You can use this code:
form name="form1" action="TestAccess.htm"
input type="button" class="center" value="Log In" onclick="butCheck_onclick()"
function butCheck_onclick() {
// do validation returnig false if something is wrong
// when all is good submit the form
form1.submit();
}
IMPORTANT notes:
You force your users to have
javascript enabled. Maybe this is
not a problem in your project.
Do you realize that anyone who does a
"View source" will see the usernames
and passwords?
What's the purpose of JavaScript embedded passwords? "As is" anyone can see these just by doing "View Source"?
But basically you need return false not FROM within for loop but AFTER if your condition fails

Categories

Resources