1

I need to validate a URL field for an input field that deals with a finicky API that will accept URL strings in a very certain format - no www's and no http's attached to the start of the string, or it breaks. A javascript handler grabs the data from the validation.php file. I have everything working except for one field.


So, for example I want

example.com/example

and

example.com

to pass validation, but I want

http://example.com/example

and

http://www.example.com/example

and any variation including any derivation of http:// or www. to not validate.


The regex I have below currently allows any type of URL including http and www. I want it to ONLY allow the above type of URL string, but not sure how to go about this.

    // API URL VALIDATION
    if ($formfield == "api_url") {
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $value)) {
            echo "Please enter your URL without the http://www part attached" 
        } else {
            echo "<span>Valid</span>";
        }

}

Any ideas?

1
  • so remove the first part of the reg exp or Remove the part you do not want in code. Just chop off the part you do not want and reset the value of the textbox. Commented Mar 30, 2015 at 15:56

3 Answers 3

3

You can use this simple negative lookahead based regex in preg_match:

~^(?!https?://)(?!www\.).+$~i

RegEx Demo

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

Comments

0

You can try to "not match" a subject that begins with http or www:

if(!preg_match('/^((http|ftp)s?:\/\/)?(www\.).+?/', $value))

Comments

-1

You can do it with .htaccess mod rewrite rule. But in your case it looks like you need to validate a input field so it doesn't apply to all cases. Here is function which will allow/dis-allow such protocols in the url.

function remove_protocol($url) {
   $filter_protocol = array('http://', 'https://', 'http://www');
   foreach($filter_protocol as $d) {
      if(strpos($url, $d) === 0) {
         return str_replace($d, '', $url);
      }
   }
   return $url;
}

in the $filter_protocol array you can keep on defining protocols not to allow in urls for instance ftp://

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.