Create mask to accept only links containing HTTP/HTTPS - Java JSF

Asked

Viewed 72 times

0

I need to create a field input where the user will place a link, but this field can only accept links that contain http:// or https:// at first. There is a way to do a validation in Javascript or Jquery to check if the link contains http:// or https:// and if not, display an error message?

1 answer

0

If you make a <input type="url"> maybe I’ll fix it.

But if you want in javascript, here’s an example:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form class="form">
            <input type="text" id="url">
            <button type="submit">Enviar</button>
        </form>

        <script>
            function checkurl(str)
            {
              regexp =  /^(?:(?:https?):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
                    if (regexp.test(str))
                    {
                      alert("Endereco ok");
                      return true;
                    }
                    else
                    {
                      alert("Insira um endereco valido.");
                      return false;
                    }
            }

        </script>
        <script>
            $('.form').on('submit', function () {
                var url = document.getElementById("url").value;
                checkurl(url);
            });
        </script>




    </body>
</html>

Browser other questions tagged

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