Check if String contains URL using JavaScript

Last Reply 5 months ago By chetan

Posted 5 months ago

Client filled the form and i got the mail of filled details:

Address : Office 366, Zine Square 6, Business Bay, Https://Www.Luxuryproperty.Com/

As you can see,client used the url link in address field.

Is it Possible that we can write javascript for not accepting url link (http://,www)?

So when client enters any text like Https://Www.Luxuryproperty.Com/, the javascript message should display saying http or www links not allowed.

Any help will be appreciated.

Posted 5 months ago

Hi chetan,

Use regular expression to check the statement.

Refer below code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        function CheckUrl() {
            var text = document.getElementById('txtStatement').value;
            if (new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(text)) {
                alert("Url is present in this statement");
            }
            else {
                alert("Url not is present in this statement");
            }
        }
    </script>
    <input type="text" id="txtStatement" style="width: 450px;" value="Office 366, Zine Square 6, Business Bay, https://www.Luxuryproperty.Com/" />
    <input id="btnCheck" type="button" value="Check Url" onclick="CheckUrl()" />
</body>
</html>

Demo


Posted 5 months ago

i slightly modified your javascript and it worked:

function CheckUrl() {
    var text = document.getElementById('<%=addtxt.ClientID%>').value;
    if (new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(text)) {
        alert("Url is not allowed in address field");
        return false;
}