I have a textbox on my website where I want to prevent any form of html input. I obviously already block it on the server side, but I also want to block it using javascript for multiple reasons. I did a quick Google search to see if there was some ready made function available but I couldn't find any.
Does anyone know how to do this?
Edit: Sorry if the question was not clear. I basically want to show an error when the user types html into the textbox and then tries to submit the form. The server is already programmed to reject HTML input from the textbox but I also want to prevent it on the client-side.
HTML
<textarea id='noHTML'></textarea>
JS
var ta = document.getElementById('noHTML');
ta.onkeyup = function (e) {
var val = this.value;
// alternate regexp /<\/*(p|div|span)\s*.*>/g
// fill the above regex with all html tags
if(val.match(/<\/*[^<>]\s*.*>/g)) {
// alert('no html');
// don't want an alert ? you can replace all html expressions
// alternate syntax for all entities
// this.value = val.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
// its long and slow but the choice is yours
this.value = val.replace(/</g, '<').replace(/>/g, '>');
}
}
You can test and play with it at jsfiddle;
it's a light solution to your problem. my suggestion to you is to replace the entities during the form submission or if you don't want it at all you can alert the user on input.
Related
I'm currently working in user creation login page for an e-commerce and I need to achieve something like this: https://drive.google.com/file/d/1JJBeZG-oyzrh8vCDRMjfv03oGDjrWwZw/view?usp=sharing (The video has to be seen on fullscreen, otherwise it'll be too small to detail anything)
Thing is I should not allow any special characters when the form is submitted and I think I already solved that:
$('#login_form #document').on('input', function() {
this.value = this.value.toLocaleUpperCase();
let count = this.selectionStart,
regex = /[^a-z0-9]/gi,
value = $(this).val();
console.log(value)
if(regex.test(value)) {
$(this).val(value.replace(regex, ''));
count--;
}
this.setSelectionRange(count, count);
});
But I can't really think in a way to show the dots and hyphens and not allowing them on submit.
Also, any recommendation to improve the code will be well receive. Thanks in advance!
Just keep the formatting from your front-end, do some reverse reformatting in backend instead, example you input 10,000.00 then you submit it using backend PHP just replace "," str_replace(',', '', '10,000.00') then you will get 10000.00 then use $new_number = (float)10000.00
$input_number = '10,000.00';
$input_number_no_comma = str_replace(',', '', $input_number);
$input_number_new = (float)$input_number_no_comma;
echo $input_number_new ;
I want to build a webpage/ custom search engine that will take user input and then query google for the results, except that with a number of keywords I want to append some predefined strings that ( will be stored in a dictionary/file..).
I tried using a form and then submitting query to google, but I want to do it as beautifully (and much the same way) as these people have done.
They just append Zlatan at the beginning , I want to append variable strings.
To show you what I've tried, here is the link to GitHub: https://github.com/google/google-api-php-client/blob/master/examples/simple-query.php
Any useful links, knowledge , suggestions, steps would be heartily appreciated.
This is how they do it. Just do the same but append any word from you list of words as you like. It's not clear how you're supposed to select what words to add. Specify that and we can be more helpful.
var form = document.querySelector('form');
var input = document.getElementById('field');
form.addEventListener('submit', function(ev) {
ev.preventDefault();
var redirect = 'https://google.com/search?q=zlatan+' + input.value;
window.location = redirect;
});
If user enters his text in the text box and saves it and again what's to add some more text he can edit that text and save it if required.
Firstly if user enters that text with some links I, detected them and converted any hyperlinks to linkify in new tab. Secondly if user wants to add some more text and links he clicks on edit and add them and save it at this time I must ignore the links that already hyperlinked with anchor button
Please help and advice
For example:
what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/ for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br>http://www.stackoverflow.com/<br> <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg<br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>
Test URL's
http://www.stackoverflow.com/
http://stackoverflow.com/
https://stackoverflow.com/
www.stackoverflow.com
//stackoverflow.com/
<a href='http://stackoverflow.com/'>http://stackoverflow.com/</a>";
I've tried this code
function Linkify(what) {
str = what; out = ""; url = ""; i = 0;
do {
url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
if(url!=null) {
// get href value
href = url[0];
if(href.substr(0,7)!="http://") href = "http://"+href;
// where the match occured
where = str.indexOf(url[0]);
// add it to the output
out += str.substr(0,where);
// link it
out += ''+url[0]+'';
// prepare str for next round
str = str.substr((where+url[0].length));
} else {
out += str;
str = "";
}
} while(str.length>0);
return out;
}
Please help
Thanks.
here is a regex where you select all the links without having anchors
(?:(?:http(?:s)?(?:\:\/\/))?(?:www\.)?(?:\w)*(?:\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))
Here is a RegExFiddle (updated 14:41)
quit a lil difficult task because in javascript you don't have a preceded by statement. :)
EDIT1: Now it detects...
http://www.abc.xy
http://abc.xy
https://www.abc.xy
https://abc.xy
www.abc.xy
abc.xy
EDIT2:
Here is it a little shorted and the usage fiddle
Regex
/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g
function
function Linkify(str) {
var newStr = str.replace(/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g,'$1');
return newStr;
}
var newData = Linkify(data);
WORKING JS-FIDDLE
EDIT 1.000.000 :D
/((http(s)?(\:\/\/))?(www\.)?([\w\-\.\/])*(\.[a-zA-Z]{2,3}\/?))(?!(.*a>)|(\'|\"))/g
this solves your problem now.
the only problem you will run in here is, 4 letters after a dot is not selected. e.g .info if you want them selected than change {2,3} to {2,4} BUT be carefully... if someone adds a text like my name is.john than is.john will be translated to a link.
EDIT 2.0
If you have a really complex URL like the following
((http(s)?(\:\/\/))?(www\.)?([\a-zA-Z0-9-_\.\/])*(\.[a-zA-Z]{2,3}\/?))([\a-zA-Z0-9-_\/?=&#])*(?!(.*a>)|(\'|\"))
Matches
https://stackoverflow.com/questions/34170950/summernote-inserthtml?firstname=channaveer&lastname=hakari#fsdfsdf
A more simple solution is probably to strip the links which you created (so the user gets exactly what they typed when they click "Edit" again).
Another idea is to split the string at </a>. That gives you a list of strings which all end with an anchor element (except the last one). Iterate over this list, cut away the part after the last <a, linkify.
I have a text field where user can fill href tag script which I have to show as a link later on. But your can enter some malicious script like alert message and more like that which will cause execution on unwanted script at the point where I use that text field value to display.
My question is that how can I restrict user to only enter href tag releated entry in text field and restrict other script to enter.
Thanks In advance.
use regular expression
var urlmatch= /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
var textboxValue = textbox.value;
if(textboxValue.match(urlmatch)){
// return true
} else {
// return false;
}
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
U need to check whether string is url , if its url accept else reject .. the below links will help ur cause. How to detect whether a string is in URL format using javascript? check if string contains url anywhere in string using javascript
I'm developing a contentEditable region on my website, where users will be able to type messages to each other.
<div contentEditable="true" class="smartText">User types here...</div>
The thing is, we will have smart text inside, meaning that if a user type #usersame inside this div, the #username should be highlighted in blue if the username exist and green if he doesn't exist. And of course all of this should happen as the user types...
I have no idea where to start, right now I have this:
$("body").on("keyup",".smartText",function(){
var $this = $(this),
value = $this.html(),
regex = /[^>]#\S+[^ ]/gim;
value = value.replace(regex,"<span style='color:red'>$&</span>");
$this.html(value);
});
But the text keeps jumping (as well as the caret position) and doesn't feel like the right direction. I guess it's a little similar to JSFiddle which colors code as it finds it.
I basically want the same thing as Twitter has.
Here is a JSFiddle to play around with: http://jsfiddle.net/denislexic/bhu9N/4/
Thanks in advance for your help.
I liked this problem and I worked very hard to solve. I believe I have finally succeeded (with a little assistance).
= UPDATED =
Piece of Code:
[...]
// formatText
formatText: function (el) {
var savedSel = helper.saveSelection(el);
el.innerHTML = el.innerHTML.replace(/<span[\s\S]*?>([\s\S]*?)<\/span>/g,"$1");
el.innerHTML = el.innerHTML.replace(/(#[^\s<\.]+)/g, helper.highlight);
// Restore the original selection
helper.restoreSelection(el, savedSel);
}
[...]
// point
keyup: function(e){
// format if key is valid
if(helper.keyIsAvailable(e)){
helper.formatText($this[0]);
}
// delete blank html elements
if(helper.keyIsDelete && $this.text()=="") {
$this.html("");
}
}
Screenshot:
JSFiddle here: http://jsfiddle.net/hayatbiralem/9Z3Rg/11/
Needed External Resources:
http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-core.js
http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-selectionsaverestore.js
Helper Question (thanks): replace innerHTML in contenteditable div
Regex Test Tool (thanks): http://www.pagecolumn.com/tool/regtest.htm
Keep in mind that the HTML markup typed by the user could be quite surprising, e.g: <span>#use</span><span>rname</span>, which still looks like #username to the user.
To avoid the crazy caret behavior (and some other nasty side effects) inside a contentEditable element, you should use W3C DOM API and walk the DOM tree each time there is a change in HTML (you can sniff the change by polling body.innerHTML upon a timer).
I've recently answered a similar question for CKEditor and described the algorithm of how to build a text-to-node map of the DOM, for finding a text match. The CKEditor DOM API is quite similar to the W3C one, you can adapt the same algorithm.
Once the match has been found, you should use DOM Range API to manipulate the content of the DOM nodes. E.g., to wrap a run of plain text with a styled <SPAN>:
var range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
var span = document.createElement("span");
span.style.backgroundColor = "blue"
range.surroundContents(span);
Overall, this task is quite non-trivial and certainly isn't something you can fit into a single page of JavaScript code, to be answered here.
This seems to be somewhat a solution to your problem.
DEMO here: http://jsfiddle.net/bhu9N/5/
$(document).ready(function() {
$("body").on("keyup", ".editable", function(e) {
var $this = $(this);
if(e.keyCode==32) {//space
var words = $this.text().split(' ');
var lastword = $.trim(words[words.length-1]);
var reg = /^#\S+/;
if(reg.test(lastword)) {
//make an AJAX call for checking this word for existence
//suppose data is returned and data==1 means green
var data = 1;
if(data==1) {
var orgtext = $this.html();
orgtext = orgtext.replace(lastword, '<span class="green">'+lastword+'</span>');
$this.html(orgtext);
}
}
}
});
});
Once the text is highlighted, the cursor goes to the starting of the div. So this still needs to be fixed. I will be updating the solution if I am able to find it. Meanwhile, just play around with what I have provided now and see if it helps.
As Ezos pointed out in his answer, I would not recommend trying to do anything intensive (such as making Ajax requests to check if a username exists or not) each time the user releases a key. You might have a bad time. With that said, I would recommend waiting a set amount of time after the user has stopped typing to run through what they've typed and highlight words, for example:
var textarea = $(".smartText");
var highlightWords = function highlightWords() {
var original = textarea.text();
var replaced = original.replace(/#[a-zA-Z0-9]+/g, function (username) {
// Magic
return "<span class='exists'>" + username + "</span>";
});
textarea.html(replaced);
};
var timer;
textarea.keyup(function (e) {
clearTimeout(timer);
if ($(this).text()) {
timer = setTimeout(highlightWords, 1000);
}
});
Link to a fiddle: http://jsfiddle.net/neJLW/
I think the code above should get you started in the right direction. Like you said, the cursor will still jump around so you'll have to save it and reset it in its old position each time you edit the contents of the div. Also, you'll want to adjust the timeout according to how long you expect determining if a username exists to take. You'll need to replace // Magic with your username check and adjust the return value accordingly.
As an aside, you'll want to keep in mind the accessibility issues with wrapping certain things in spans (see this GitHub issue for Lettering.js for an example).
Edit: Also note that this is not a robust solution (it doesn't react to copy paste for example). YMMV.
The method you are using seems very browser intensive and may cause some issues if someone types very quickly and it's running multiple requests before the 'String' can be verified through ajax. You might be better off if you use a library such as http://aehlke.github.io/tag-it/ - You can depict a function to change font color, etc, the same way it recommends a tag.
If i get time, i will make fiddle demo.