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.
Asked
Active
Viewed 594 times
0
3 Answers
3
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;
}

thecodejack
- 12,689
- 10
- 44
- 59
-
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 Aug 28 '13 at 08:24
-
That is I want only two things either href contained script or any string that is not a HTML malicious script :( – Satish Sharma Aug 28 '13 at 08:34
-
so when it doesnt match to regexp which in your case will be script it will return false... – thecodejack Aug 28 '13 at 12:01
-
1Thanks 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. – Satish Sharma Aug 30 '13 at 07:16
0
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}

Arvind Bhardwaj
- 5,231
- 5
- 35
- 49
-
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). – Satish Sharma Aug 28 '13 at 08:50
0
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

Community
- 1
- 1

codebreaker
- 1,465
- 1
- 12
- 18
for(var i = 0; i < 5; i++) alert('Hello!!');
" script. means – Satish Sharma Sep 03 '13 at 11:23