Validate Http and Https Url using RegularExpression (Regex) in JavaScript

Last Reply on Mar 16, 2014 11:39 PM By Mudassar

Posted on Mar 16, 2014 11:18 PM

I need to implement URL Validation using Javascript in MVC4. Here is my code .

var regexp = "^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
return regexp.test(URLValue);

but its not working in MVC 4. i thought test operation is not supported for MVC. Is there any solution to implement validation using Javascript.

 

Posted on Mar 16, 2014 11:39 PM

You have not created a RegExp object and hence don't see test method

<input type = "text" id = "txtUrl" value = "http://www.aspforums.net" />
<input type = "button" value = "Validate" onclick = "Validate()" />
<script type="text/javascript">
    function Validate() {
        var regexp = new RegExp("^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$");
        var url = document.getElementById("txtUrl").value;
        if (!regexp.test(url)) {
            alert("Not valid Url!");
        } else {
            alert("Valid Url!");
        }
    }
</script>

Demo

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html