Ensure that the Bootstrap form validation checks for both an empty field and a valid URL

I'm currently working on validating a form field in Bootstrap 4.4. The goal is to not only check if the field is filled out, but also to ensure that it contains a valid URL. This URL can be an internal link, a hostname, or an IP address. However, it must be entered in the format of or , and not just XXXXX.com. The code I have right now is not performing the validation correctly.

Here is the initial HTML form I am working with:

<form method="post" class="needs-validation">
<div class="input-group">
    <INPUT TYPE="TEXT" class="form-control validationUrl" PLACEHOLDER="http://yourwebsite" required>
        <div class="valid-feedback">
            Looks good!
        </div>
        <div class="invalid-feedback">
            Must begin with http
        </div>
    <div class="input-group-append">
        <INPUT TYPE=SUBMIT class="btn btn-primary" VALUE="GO">
    </div>
</div>
</form>

This form currently prevents submission if left blank. I am aiming to validate that the submitted value is not empty and is a valid URL starting with http.

One helpful resource I found is a Stack Overflow post on URL validation code: JS Regex url validation which provides the following code:

function isUrlValid(userInput) {
    var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    if(res == null)
        return false;
    else
        return true;
}

I have also incorporated Bootstrap's validation code from their documentation page: https://getbootstrap.com/docs/4.0/components/forms/

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
        }
        form.classList.add('was-validated');
    }, false);
    });
}, false);
})();
</script>

I have tried to modify the code to include URL validation, but it is not functioning as expected. It is allowing any input to be submitted without validation.

Here is the current code I am working on:

<form method="post" class="needs-validation">
<div class="input-group">
    <INPUT TYPE="TEXT" class="form-control validationUrl" PLACEHOLDER="http://yourwebsite" required>
        <div class="valid-feedback">
            Looks good!
        </div>
        <div class="invalid-feedback">
            Must begin with http
        </div>
    <div class="input-group-append">
        <INPUT TYPE=SUBMIT class="btn btn-primary" VALUE="GO">
    </div>
</div>
</form>


<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('validationUrl');
    var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(res, function(res) {
    form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
        }
        form.classList.add('was-validated');
    }, false);
    });
}, false);
})();
</script>

Answer №1

Ensure the field is not empty by including the required attribute.

To validate that it is a proper URL, use type="url" instead of type="text".

Example:

<INPUT type="url" class="form-control validationUrl" placeholder="http://yourwebsite" required>

Additionally, you can make the URL validation stricter by adding the pattern attribute.

For more information, refer to the official documentation here.

Answer №2

Test out this JavaScript code to see if it functions correctly.

`function checkInput() {
  var input = document.forms["myForm"]["text"].value;
  if (input == "") {
    alert("Input must not be empty");
    return false;
  }
}`

Next, include the following code in your form to trigger the function when the submit button is clicked.

onsubmit="return checkInput()"

In this case, "myForm" represents the form name and "text" represents the input field you want to validate.

The if statement can be customized for different validations. For instance, to check if the input starts with a specific string, you can utilize the substring method.

    `function checkInput() {
      var input = document.forms["myForm"]["text"].substring(0,6);
      if (input !== "https:") {
        alert("Please enter a valid URL");
        return false;
      }
    }`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting several sticky titles after displaying and hiding elements

Inspired by a popular codepen example, I have successfully implemented sticky titles in my sidebar. However, when integrating these sticky titles with the functionality to show/hide related items on click, I encountered some unexpected issues. The code sni ...

"An error occurs when attempting to clear Rad Grid data with javascript: htmlfile: Invalid argument thrown

Hello, I am currently developing an ASP.NET application. I am facing an issue where I need to clear the data in a Rad grid upon button click using JavaScript. The code snippet that I have attempted for this is as follows: document.getElementById(&a ...

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

What is the best way to display a form within every row of a data table?

I am currently working on a page that retrieves data from a backend and displays it in a Datatable. One of the columns in my table is an input field with a default value fetched from the backend, and another column contains buttons. How can I implement a f ...

Exploring real-time data updates using React and the setInterval method

Every time my component loads, I am attempting to continuously poll the Spotify API using setInterval. However, during testing, an error message pops up: Invalid Hook Call..etc. I suspect that the issue stems from using useEffect within another useEffect w ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

Utilizing every function across various offspring

Is it possible to use the each function on multiple children at once? The code below shows my attempt to use the each function on both child elements in a single line. $('.right .submission:not(:first)').each(function(){ stud ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

Can object methods be called using inline event attributes in an HTML tag?

Exploring the depths of core JavaScript has been my latest obsession. It's fascinating how we can easily trigger functions within the global context using events like this. HTML <span class="name" onclick="clicked()">Name</span> JavaSc ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Acquiring the class function from a service which yields a model

Within my class called userName, I have defined properties that form a model when casting from json. Additionally, this class includes a simple function that returns the full Name: export class userName { firstName: string; lastName: string; g ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

Why does the request for server parameter 'occupation=01%02' function correctly, while 'occupation=01%2C02' or 'occupation=01&occupation=02' result in an error?

There seems to be an issue with the parameter when using the API to request data from the server. The value 'occupation=01%02' works correctly when entered directly into the browser URL, but errors occur when using 'occupation=01%2C02' ...

Experiencing issues with implementing shopping cart logic using KnockoutJS. Need help

The Objective Create a dynamic list of products. The Scenario Overview In my online shopping application, I want to showcase the products I add to my shopping list in a sidebar when I click the 'add button' for each product. Brief Problem Sum ...

I'm struggling to get the Bootstrap collapse navbar-collapse feature to work in my Angular

My attempt at implementing the bootstrap collapse navbar-collapse feature in my Angular 8 project seems to be not working correctly after compilation. I have already installed: bootstrap - 4.3.1 and made changes to the angular.json file. I also have jquery ...

Symfony2's W3C XHTML validation fails when validating form submissions according to the W3C standards

Having an issue with valid w3.org XHTML - the validator is showing an error on the required attribute of an input: The attribute "required" is not recognized. I firmly believe that this attribute is necessary, as it is included by Symfony2 form builder f ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Is it necessary to decode the JSON data stored in the variable?

Consider the code snippet below: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var responses = JSON.parse(this.responseText); var ...