2

I'm creating a reg exp for validating only those URLs from the list where parameter p has a value between 100 and 9999. So from the list given below, only 3rd and 4th URL need to return true as output when they are entered into a textbox.

http://www.website.com/our-resources/news/?p=1
http://www.website.com/example/voice-of-the-customer/news/?p=12
http://www.website.com/our-resources/news/?p=123
http://www.website.com/example/?p=4321
http://www.website.com/example/products/touchchat/news/?p=12345

HTML

<input type=url/>
<button>Validate</button>
<div id=status></div>

Javascript

$('button').click(function(){
    var val = $('input').val();
    var regex = /^(https?:\/\/)?[a-z0-9-]*\.?[a-z0-9-]+\.[a-z0-9-]+(\/[^<>]*)?$/;
    var isValid = regex.test(val);
    $('#status').text(isValid);
});

But this regex returns true for all URLs. What changes should I make to this expression?

FIDDLE

Smokey
  • 1,857
  • 6
  • 33
  • 63
  • Do you also have to check if all of them are valid URLs? – gurvinder372 Jan 18 '18 at 10:25
  • Yes, that too but only return true for those urls having value of p between the range i mentioned. I'm validating all urls using that expression but range check aint happening. @gurvinder372 – Smokey Jan 18 '18 at 10:27
  • 1
    To test regexes you write please checkout: https://regexr.com/ It's a fancy website to test if your regex is valid and matches everything as desired :) – Piotr Styczyński Jan 18 '18 at 10:34

4 Answers4

2

A simpler solution would be to retrieve the querystring parameter from the URL then check to see if its value meets your bounds:

$('button').click(function() {
  var p = parseInt(getParameterByName('p', $('input').val()), 10) || 0;
  var isValid = p >= 100 && p <= 9999;
  $('#status').text(isValid);
});

function getParameterByName(name, url) {
  if (!url)
    url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results)
    return null;
  if (!results[2])
    return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
body {
  font: 10pt Verdana;
}

input {
  width: 100%;
  display: block;
  margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="url" value="http://google.com/" />
<button>Validate</button>
<div id="status"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You can make use of URL

var fnGetURL = ( strURL ) => {
   try
   {
      return new URL( strURL );
   }
   catch(e)
   {
      return null;
   }
};

And get searchParams if null is not returned

var fnIsValidURL = ( strURL ) => {
   var url = fnGetURL( strURL );
   if ( url )
   {
      var p = +url.searchParams.get("p");
      return p >= 100 && p <= 9999;
   }
   return false;
};

Demo

var fnGetURL = (strURL) => {
  try {
    return new URL(strURL);
  } catch (e) {
    return null;
  }
};


var fnIsValidURL = (strURL) => {
  var url = fnGetURL(strURL);
  if (url) {
    var p = +url.searchParams.get("p");
    return p >= 100 && p <= 9999;
  }
  return false;
};

var urlArr = ["http://www.website.com/our-resources/news/?p=1",
"http://www.website.com/example/voice-of-the-customer/news/?p=12",
"http://www.website.com/our-resources/news/?p=123",
"http://www.website.com/example/?p=4321",
"http://www.website.com/example/products/touchchat/news/?p=12345"];

urlArr.forEach( function(url){
   console.log( url, fnIsValidURL(url) ); 
});
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • 2
    An ideal solution in a perfect world, but be aware that `URL()` has no support at all in IE and `searchParams` is unsupported in Edge and Safari: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility – Rory McCrossan Jan 18 '18 at 10:44
0

Try this out:

function isValidParam(url) {
    if ($.urlParam('p',url) > 99 && $.urlParam('p',url)<10000) {
        return true;
    }
    return false;
}

Call above method to check URL validity

$.urlParam = function(name,url) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)')
            .exec(url);
    if (results == null) {
        return null;
    } else {
        return results[1] || 0;
    }
};
jeet427
  • 538
  • 3
  • 16
0

It may be too simple but I found this regex working fine for what you're looking for.

/(?:http://[\S]*)\/\?p=(\d{3,4})$/g
Hiplobbe
  • 138
  • 6