How to check if the url is true

Asked

Viewed 880 times

0

I made this code simple to encode urls, but I would like it to work only with url checking if the protocol and hostname are correct or if the magnetic link is correct:

http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:  //url magnético

function codificar() {
    var valor = document.getElementById("teste").value;
    var encode = window.btoa(valor);
    
    document.getElementById("saida").innerHTML = encode;
}
<p>Clique no botão para codificar a url.</p>
<br>
<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>
<br>
<br>
<textarea style='width:150px; resize: none;' id="saida"></textarea>

  • You want to check whether the url have the patterns you quoted?

  • Yes exactly that

2 answers

3


You may be checking if your strings belong to a pattern using regex. Follow an example of a er (regular expression) and how would your use:

  var re = new RegExp("^((http(s?):\/\/(www.)?[a-z]+.com\/)|(magnet:\?xt=urn:btih:))")

  var term = "http://www.exemplo.com/"

  if (re.test(term)) {
    alert("Valid");
  } else {
    alert("Invalid");
  }

The way that er was built, she will accept any string start with these patterns:

http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:

That is, if you have this pattern at the beginning of string, anything that is after the .com/ in the cases of url and of btih: in the case of magnet link, it will accept. As for example:

http://www.exemplo.com/qualquercoisaaquiassim/?-thiagorespondeu

0

You can use this full code below if you need to .net .org .xyz etc.. and is working perfectly with the magnetic url. It will check the expression if invalid will return an alert.
If you need to add ftp add here (ftp|http|https), the "| or ||" is the logical operator corresponding to ou.

function codificar() {
	var reg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?|magnet:\?xt=urn:btih:/
	var valor = document.getElementById("teste").value;
	var encode = window.btoa(valor);

	if (reg.test(valor)) {
		document.getElementById("saida").innerHTML = encode;
	} else {
		alert("Url Invalido");
	}
}
<p>Clique no botão para codificar a url.</p>
<br>
<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>
<br>
<textarea style='width:150px; resize: none;' id="saida"></textarea>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.