1

I need to flag a textarea that contains a URL starting with http://, but not with https://. I thought this should work, but I'm getting the alert even when all URLs are https.

$('#template_form').submit(function() {
    alert("this is the text: " + $("#template_data").val() );
    val = $("#template_data").val();
    if (val.search(/^http:\/\//)){
        alert("there's a URL in there...");
        return false;
    }
    return true;
});

<textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>

This should only present the second alert if the URL were http://www.test.com, but it's throwing it even as is, with https://. What am I doing wrong?

3
  • Why can't you just try with \http:\g ? Commented Oct 4, 2016 at 16:32
  • 2
    search returns -1 for no match, which evaluates to true. Commented Oct 4, 2016 at 16:34
  • If you want a boolean use regexp.test(string). Commented Oct 4, 2016 at 16:36

3 Answers 3

1

From the documentation for search():

A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.

-1 will make the if statement evaluate to true (if (-1) {alert("true");}. So either switch to match() or test(), or check for if (val.search(...) > -1)

Also the ^ is wrong in your regex, it would only match from the start of the string.

$('#template_form').submit(function() {
  alert("this is the text: " + $("#template_data").val());
  val = $("#template_data").val();
  if (val.match(/http:\/\//)) {
    alert("there's a URL in there...");
    return false;
  }
  return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="template_form">
  <textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>
  <input type="submit" value="submit">
</form>

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

Comments

0

String.search() is not boolean:

Return value
The index of the first match between the regular expression and the given string; if not found, -1.

Further in that same piece of documentation:

When you want to know whether a pattern is found and also its index in a string use search() (if you only want to know it exists, use the similar test() method, which returns a boolean)

Comments

0
$('#template_form').submit(function() {
  if ($("#template_data").val().indexOf("http:\/\/") > -1) {
    return false;
  }
  return true;
});

Here is another way.

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.