Bootstrap form validation - check that field is not blank, and includes valid URL

Viewed 2354

I'm attempting to validate a Bootstrap 4.4 form field. I don't just want to verify that this field is populated, I also want to verify that it's populated with a URL. This can be an internal URL, a hostname or an IP address, however it should be entered as http://XXXXXX or https://XXXXXX, and must not be just XXXXX.com. My current code (last section of this post) does not validate the form correctly.

Here's the html form that I'm starting 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 in itself will prevent the form from being sumbitted blank. I'm trying to test if the submitted value: 1. is not blank, and 2. is a URL (starting with http).

There are some useful Stack Overflow posts with URL validation code, like this one: JS Regex url validation which gives us 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've then taken the starter bootstrap validation code found here: 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've hacked together the following, however it's not doing any validation at all. It will allow anything to be submitted.

Current work in progress code I'm trying to fix:

<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>
2 Answers

Try this JS, and see if it works.

`function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}`

You then add the following to the form, which will call the function when the submit button is clicked.

onsubmit="return validateForm()"

the myform value is the name of the form and the fname value is the name of the input you wished to be checked.

The logic of the if statement can be used to give a slew of validations. If you want to check if the first 7 characters of the input is something specific, you can use the substring class.

    `function validateForm() {
      var x = document.forms["myForm"]["fname"].substring(0,6);
      if (x !== "http://") {
        alert("please enter a valid URL");
        return false;
      }
    }`

To make sure the field is non-empty -> add required attribute.

To make sure it's a valid url -> Instead of type="text", try the attribute type="url"

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

Note: You can also add pattern attribute to make the url matching more strict.

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url

Related