Javascript and PHP verify that the URL address entered by the user is correct

  • 2021-07-21 08:02:29
  • OfStack

This article describes the example of Javascript and PHP validation user input URL address is correct method, share for your reference. The specific methods are as follows:

1. javascript detects URL address validity:

<script type="text/javascript">
function checkUrl() {
 var url = document.getElementById('url').value;
 if (url==''){
  alert('URL Address cannot be empty ');
 return false;
 } else if (!isURL(url)) {
  alert('URL The format of should be https://www.ofstack.com');
 return false;
 } else {
  return true;
 }
 return false;
}
function isURL(str)
{
 //varreg=/[0-9a-zA-z]+.(html|htm|shtml|jsp|asp|php|com|cn|net|com.cn|org)$/;
 // Must contain .( Back face 1 A . At least in front 1 Characters ) And . At least in the back 1 Word characters, and finally 1 Characters must be word characters or /
 varreg=/w+.(w+|w+/)$/;
 varisurl=reg.test(str);//test(str) The method is js The built-in object of the correct expression can be called directly
 returnisurl;
}
</script> <form action="" method="post" onsubmit="checkUrl();">
 URL:
 <input type="text" name="url" id="url" value="https://www.ofstack.com"  onfocus="this.value=''"/>
 <br /><br />
 <input type="submit" value=" Get the address " name="get"/>
 <input type="submit" value=" Download " name="download"/>
</form>

2. PHP Detects URL Address Validity

<?
function is_url($str){
return preg_match("/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*([^<>"])*$/", $str);
}
?>

If you want to try the normal method, we can use the file_get_contents () function to verify it.

I hope this article is helpful to everyone's PHP programming.


Related articles: