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

3
  • Do you also have to check if all of them are valid URLs? Commented Jan 18, 2018 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 Commented Jan 18, 2018 at 10:27
  • 1
    To test regexes you write please checkout: regexr.com It's a fancy website to test if your regex is valid and matches everything as desired :) Commented Jan 18, 2018 at 10:34

4 Answers 4

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>

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

Comments

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) ); 
});

1 Comment

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: developer.mozilla.org/en-US/docs/Web/API/…
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;
    }
};

2 Comments

No need to call urlParam twice with the same arguments. Cache the result and make it simpler.
I know. I just hinted you how to make it better.
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

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.