EmmyS EmmyS - 2 months ago 10
Javascript Question

Regex for http:// but not https://

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?

Answer

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>