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.

5
  • 1
    stackoverflow.com/questions/8667070/… Commented Apr 2, 2013 at 6: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 // Commented Apr 2, 2013 at 6:25
  • Please rephrase your question or/and add an example. Commented Apr 2, 2013 at 7:40
  • Please further explain "filepath like \abc". The (\\\\)+ in your regex will match any string beginning with an even number of backslashes. Commented Apr 2, 2013 at 13:18
  • @MikeM please check now Commented Apr 2, 2013 at 15:18

3 Answers 3

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.

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

Comments

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.

Comments

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.

2 Comments

this solution fails when user enters values like http:/ or dfdfhttp:// or ////
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.

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.