ASP.NET - 'web site url' validation in javascript

Asked By Anandh Ramanujam on 07-Dec-10 04:55 AM
Hi,

How can we validate the 'web site url' in javascript...

Can anybody help me in this regard.

Thanks.
Jatin Prajapati replied to Anandh Ramanujam on 07-Dec-10 04:56 AM
try this function

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
Reena Jain replied to Anandh Ramanujam on 07-Dec-10 05:21 AM
hi,

there are two eg for you
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function Validate(form) {
  var v = new RegExp();
  v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
  if (!v.test(form["URL"].value)) {
    alert("You must supply a valid URL.");
    return false;
  }
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="MyForm" ACTION="MyFile.php" METHOD="POST" onSubmit="return Validate(this);">
<INPUT TYPE="TEXT" NAME="URL" VALUE="http://">
<INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT">
</FORM>
</BODY>
</HTML>
or
<html>
<head>
</head>
<script language="javascript">
function isURL(s) {
  var regexp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
  alert(regexp.test(s));
}
</script>
<body>
  <form>
    <input type="text" name="url" size="20" id="url"/>
    <input type="button" value="Validate" onClick="javascript:isURL(document.getElementById('url').value);"/>
  </form>
</body>
</html>

in above code will checks the following :

o URL starts with a-z, A-Z (e.g. http, ftp...)
o It is then followed by ://
o next we have more letters, numbers and special chars : a-z, A-Z, 0-9, -, _
o there must be at least one "."
o A URL can contain at it's end part the more special characters and this is why the last part allows for more options such as ?, /, &, %, etc. you may add/remove chars as needed to your code.

Hope this will help you
DL M replied to Anandh Ramanujam on 07-Dec-10 05:22 AM
Try below Sample code

 <asp:TextBox ID="txtWebUrl" />

<asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server" Text="Submit" />

Now on the source code of this form in script tag write the following code:


if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")

{

alert("Web URL can not be blank");

document.getElementById("<%=txtWebURL.ClientID %>").value="http://"

document.getElementById("<%=txtWebURL.ClientID %>").focus();

return false;

}

var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"

var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;

var matchURL=tempURL.match(Url);

if(matchURL==null)

{

alert("Web URL does not look valid");

document.getElementById("<%=txtWebURL.ClientID %>").focus();

return false;

}