How can I verify that the URL is correct?

0

Good I am breaking my head with this situation and I do not even know where to start. I have a list of valid URLs for an input, let's say 10 url from where users can enter links in an input, what I'm looking for is that if the user enters a link from a URL that is not in that list, an error will appear and not Allow it to hit the Enter button, knowing that the code should only validate what is between wwww and .com or. net, since after the .com what follows is the link and that will always vary.

I have the HTML made I do not publish it because I really could not get past this point.

    
asked by Atejada 28.02.2018 в 20:19
source

1 answer

0

Use the split javascript feature when you get the url ("www.urldeprueba.com") have it separated by parts using as separator ". " and to access each part you do it with an array (I do urlSplit [0] to access the first separated text). Only subtract from there make the validations you think appropriate. For example, add the validation that starts with www and that the string that separates has at least three parts (a format www.prueba.com).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8">
 
</head>
<body>
<label>Url </label>
<input id="url" name="">
<label id="msg"></label>
<br>
<button onclick="ValidaUrl()"> Valida Url</button>
<script>
function ValidaUrl()
{
  var url =$("#url").val();
  var urlSplit = url.split(".");
  if(urlSplit.length > 2) // parametro que cambiaras segun sea la estrutura de tu url 
  {
    if(urlSplit[0] != "www")
    {
      $("#msg").text("Url Invalida");
      return;
    }
    // aqui agrega las demas condiciones para validar tu url
  }
  
}
</script>
</body>
</html>
    
answered by 28.02.2018 в 20:58