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.
-
be more specific Show your code.Nikhil D– Nikhil D2013-08-28 05:33:44 +00:00Commented Aug 28, 2013 at 5:33
-
Add server side validationArvind Bhardwaj– Arvind Bhardwaj2013-08-28 05:34:54 +00:00Commented Aug 28, 2013 at 5:34
-
This SO answer will help: stackoverflow.com/questions/822452/…Arvind Bhardwaj– Arvind Bhardwaj2013-08-28 05:35:57 +00:00Commented Aug 28, 2013 at 5:35
-
please be more specificMath chiller– Math chiller2013-08-28 05:36:26 +00:00Commented Aug 28, 2013 at 5:36
-
regular expressions can solve your problem. this can help you: stackoverflow.com/questions/280759/…Harutyun Imirzyan– Harutyun Imirzyan2013-08-28 05:37:40 +00:00Commented Aug 28, 2013 at 5:37
|
Show 1 more comment
3 Answers
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;
}
4 Comments
Satish Sharma
this is very fine regex pattern but one more issue is there I have to accept simple string also with href string and this expression is ignoring simple string :(
Satish Sharma
That is I want only two things either href contained script or any string that is not a HTML malicious script :(
thecodejack
so when it doesnt match to regexp which in your case will be script it will return false...
Satish Sharma
Thanks CodeJack I have used your regex and $(variable_name).text() concept to prevent execution on script injected and also make hyperlink to show as it is as per your regex.
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
1 Comment
Satish Sharma
but what will be the case is only simple string is passed. I have to receive either a HREF contained script or a simple string (combination of any characters, alphabets, symbols but not a html script).
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