0

(1) My example Current URL along with Parameters is ---- www.example.com?fname=John&femail=john123@example.com

(2) Through html / JavaScript I want to check Current URL Parameter whether it contains any data in fname

(3a) Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page" or (3b) If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.

I tried the following successfully :

<!doctype html> <html> <head> <body> <div> <p id ="dd"></p> </div> <meta charset="UTF-8"/> <script type="text/javascript"> var iid=document.getElementById("dd"); var getURL=window.location.href; var theString = window.location.href; var theWord = "fname"; var theWordExp = /fname/g; if (theString.search(theWordExp) == -1) { window.location.href= ('www.example.com/error-page'); }; </script> </body> </head> </html>

M. R. O.
  • 1
  • 1

1 Answers1

1

Explanation:

  • "I want to check Current URL Parameter whether it contains any data in fname"

The getQueryParam function is explained here How to get "GET" request parameters in JavaScript?

basically it's almost the same as your approach using the location href to parse the params

  • "If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)

Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method

const getQueryParam = (name) => {
  if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
    return decodeURIComponent(name[1]);
}

let fnameParam = getQueryParam("fname");
if (!fnameParam) {
  window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>

<head>

  <body>
    <div>
      <p id="dd"></p>
    </div>
  </body>
</head>

</html>