1

I need to alert user when the entered value

  1. does"t start with http:// or https:// or //
  2. if any of the above mentioned 3 words(http:// or https:// or //) were repeated in the entered value.

I tried the below regex in which the 1st case succeeds where 2nd case fails

var regexp = /^(http:(\/\/)|https:(\/\/)|(\\\\))/;
var enteredvalue="http://facebookhttp://"

if (!regexp.test(enteredvalue.value)) {    
    alert("not valid url or filepath);
}

Please help me regarding the same.

shiv455
  • 7,384
  • 19
  • 54
  • 93
  • 1
    http://stackoverflow.com/questions/8667070/javascript-regular-expression-to-validate-url – outcoldman Apr 02 '13 at 06:18
  • @outcoldman Thanks for ur link,actually as i mentioned i dont want to validate url...it just need to start with http:// or https:// or // which was working with the snippet which i posted above but need extension for the regex to even test for duplicate values like http:// or https:// or // – shiv455 Apr 02 '13 at 06:25
  • Please rephrase your question or/and add an example. – Loamhoof Apr 02 '13 at 07:40
  • Please further explain _"filepath like \abc"_. The `(\\\\)+` in your regex will match any string beginning with an even number of backslashes. – MikeM Apr 02 '13 at 13:18
  • @MikeM please check now – shiv455 Apr 02 '13 at 15:18

3 Answers3

1

This seems to work (though there will be more elegant solutions). Hope it helps at all.

var regex = /http[s]{0,1}:\/\/|\/\//;
var x = enteredvalue.split(regex);
if(!(x[0]=='' && x.length==2))
   alert("not valid url or filepath");

Cheers.

d'alar'cop
  • 2,357
  • 1
  • 14
  • 18
1

Try

var regexp = /^(?!(.*\/\/){2})(https?:)?\/\//;
var enteredvalue = "http://facebookhttp://";

if (!regexp.test(enteredvalue)) {    
    console.log("not valid url or filepath");
}

A negative look-ahead is used to prevent a match if two sets of // appear in the string.

MikeM
  • 13,156
  • 2
  • 34
  • 47
0

To check for multiple matches you could use String.match in conjunction with RegexP and the "global search" option. Below is a simplified version of your code:

var enteredvalue="http://facebookhttp://"
var test_pattern = new RegExp("(https://|http://|//)", "g"); //RegExP(pattern, [option])

enteredvalue.match(test_pattern); // should return ["http://", "http://"]

When match returns more than one instance then it is clear that the pattern is used more than once. That should help with identifying incorrect urls.

Also, it's alot cleaner than splits.

Hope this helps.

Kurt Campher
  • 745
  • 1
  • 5
  • 11
  • this solution fails when user enters values like http://http:// or dfdfhttp:// or //// – shiv455 Apr 02 '13 at 17:05
  • Yeah, hence the "Below is a simplified version". I was not focusing on the pattern more the ability to find multiple matches. Use it or don't use it. Cheers. – Kurt Campher Apr 03 '13 at 07:12