0

I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.

This is what I am running

<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
    if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the    http & https strings */ {
        $.noop() /*if strings exist, do nothing */
    }
    else {
        // get value from field
        var cur_val = $(this).val(); 
        // do with cur_val
        $(this).val('http://' + cur_val);
    }        

});

});  

</script>

This is the second function I used for validation:

<script type="text/javascript">
function validate() {
    var url = document.getElementById("url").value;
    var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    if (pattern.test(url)) {
        alert("Url is valid");
        return true;
    } 
        alert("Url is not valid!");
        return false;

}
</script>

What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.

Thank you!

1
  • Okay - are you able to get the validation function working by itself? Does the "add http" function actually produce valid URLs? Could you show us the form you are using this on (or at least the part containing the URLs?) Commented Mar 28, 2013 at 14:07

2 Answers 2

1

I don't know, if this is what you are exactly looking for,

var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

pattern.test("http://google.com");   // True
pattern.test("google.com");          // False

The if condition you are using is useless, since you return the result of the pattern match anyway.

So the updated Validate function should simply return the pattern results & should look like:

function validate() {

    var url = document.getElementById("url").value; 

    var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    return pattern.test(url);
}

Assuming that there is a DOM element with id url.

Sign up to request clarification or add additional context in comments.

Comments

0

Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.