Form validation in HTML is not showing up as expected

I'm new to HTML form validation and I'm currently trying to utilize browser defaults for this purpose. The form is designed to use a JQuery script to submit the data. Despite going through similar posts and updating my code, I am still facing issues. When I click on the Subscribe button without entering any information, no prompts are displayed.

HTML

<form class="form-inline" id="sub-form">
          <div class="flex-fill mr-2">
            <div class="mc-form-group-FNAME" style="display: inline">
              <input type="name" class="form-control required" name="FNAME" id="mce-FNAME" value="" placeholder="First name" required />
            </div>
            <div class="mc-form-group-EMAIL" style="display: inline">
              <input type="email" class="form-control required email" name="EMAIL" id="mce-EMAIL" value="" placeholder="Email address" required />
            </div>
            <button type="submit" class="btn btn-primary" id="subscribe-btn" onclick="submitForm()">Subscribe</button>
          </div>
          <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_8a28f24e93a8a23b993145f05_2d6480ea6a" tabindex="-1" value=""></div>
        </form>

JQuery/JS

  //Mail Chimp form submission
  $('#sub-form').MailChimpForm({
    url: 'https://-.us19.list-manage.com/subscribe/post?u=8a28f24e93a8a23b993145f05&amp;id=2d6480ea6a',
    fields: '0:FNAME,1:EMAIL',
    submitSelector: '#subscribe-btn',
    customMessages: {
      E001: 'This field can not be empty',
      E003: 'Please enter a valid email address',
    },
    onFail: (message) => {
      if ((message.indexOf("already") >= 0) || (message.indexOf("recent")) >=0) {
        alert('This email address is already subscribed. Stay tuned for our newsletter!')
      }
    },
    onOk: function() {
      $('#subscribe-ok').modal('show');
      $('#sub-form').each(function() {
        this.reset();
      });
    }
  });

UPDATE

In further testing, it appears that when I remove the JQuery script, the HTML validation functions properly. However, upon reintroducing the script, the validation breaks. Any insights into why my JS might be interfering with HTML validation?

Answer №1

Appreciate all the input from everyone. After considering all options, I decided to go with JQuery exclusively and integrated ToolTipster and JQuery Validate. See the finalized code snippet below.

$("#sub-form").validate({
      errorPlacement: function(error, element) {
          var ele = $(element),
              err = $(error),
              msg = err.text();
          if (msg != null && msg !== "") {
              ele.tooltipster('content', msg);
              ele.tooltipster('open'); //will only open if there is an actual error message. jQuery-validate sometimes returns a label without text, so we need to check the innerHTML.
              console.log("form validation attempted")
          }
      },
      unhighlight: function(element, errorClass, validClass) {
          $(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
      },
      rules: {
          field1: {
              required: true,
              email: false
          },
          field2: {
              required: true,
              email: true
          }
      },
      submitHandler: function(form) { // just for demonstration
          alert('valid form');
          return false;
      }
  });

//Validate the form when subscribe button is clicked
  $('#subscribe-btn').click(function () {
    if ($("#sub-form").valid()) {
            console.log('hello - valid form');
        } else {
            console.log('uh oh invalid form');
        }
    });

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

Customize the style based on the state using styled components

I am currently working with a function component that looks like this: const Navbar = ({setNav, nav}) => { const [justify, setJustify] = useState('space-around') //get localStorage const user = JSON.parse(localStorage.getItem('user& ...

Verify image loading using jQuery

<img src="newimage.jpg" alt="thumbnail" /> I am dynamically updating the src attribute of this image. Is there a way to verify if the image has been successfully loaded and take action once it is? Appreciate any guidance on this matter. ...

Mastering the art of flawlessly executing kerning-generated code

I am facing a problem while implementing logotext with kerning technique in the <header> element. I found a useful tool made by Mr. Andrew which can be accessed through this link. Before making any modifications, I had the following code in the heade ...

The Bootstrap 4 grid appears to be malfunctioning as the columns are not displaying next to each other as expected

I've implemented the code below in an attempt to achieve the desired layout shown in the image, but instead, I'm getting a different outcome. Can someone help me figure out what I might be doing wrong with the Boostrap 4 grid system? I'm co ...

Styled HTML Radio Button Failing to Register Click

When I select the radio button, it does not actually get clicked and the status of other buttons remains unchanged. The CSS code being used is as follows: input[type="radio"] { display:none; } input[type="radio"] + label { height: 20px ...

The external HTML page fails to load within a div in Firefox browser

My jquery script successfully loads an external HTML page into a div when tested on Chrome, but it's not functioning properly on Firefox. Here is the demo link. Could someone please explain why this code snippet is not working on Firefox? Code: &l ...

Preventing ElementNotVisibleException in Selenium WebDriver

Although I haven't delved into HTML extensively, I might not be entirely correct in what I'm about to discuss. As I was working on my Selenium code, I observed that certain buttons on specific webpages don't redirect to other pages but rath ...

What is the best way to switch the direction of the arrows based on the sorting order?

Is there a way to dynamically change the direction of arrows based on sorting, similar to the example shown here? sortingPipe.ts: import { SprBitType } from '../spr-bit-type/sprBitType'; import { Pipe, PipeTransform } from '@angular/core& ...

Top method for customizing w2ui grid appearance

While utilizing the w2ui grid to showcase data in a table, I've found it to be quite effective. However, I'm not entirely happy with the appearance of the table itself. Are there any methods available for styling the table that don't involve ...

Arrow not appearing when hovering over navigation bar in Bootstrap 4

My navbar is not displaying the arrow even though I added class="dropdown-toggle" data-toggle="dropdown" from w3schools.com in my anchor tag. The hover effect works, but the arrow is still not showing. html file <div class="dropdown"> ...

Modifying a Sass variable using a Knockout binding or alternative method

Is it feasible to dynamically alter a sass variable using data-binding? For instance, I am seeking a way to modify the color of a variable through a button click. I am considering alternative approaches apart from relying on Knockout.js. $color: red; ...

Updating the current date at midnight or on the new day in JavaScript can be achieved using specific date and time

I have a web watch that is supposed to work 24/7 and display the digital time along with the current day. However, my issue is that when the time passes midnight, the current day does not update and I am forced to restart the entire application. I attempt ...

Ways to incorporate validation into Material-UI form input fields

I have a react functional component that utilizes Material UI form, which includes TextField. The onChange event is managed in the "Container Component". I have added required for client-side form validation, but it doesn't seem to be working. Do I ne ...

Prevent draggable function in jQuery-UI for specific elements

I'm in the process of creating a website that mimics a desktop interface, and I want to be able to easily move around the windows. To achieve this functionality, I am incorporating jQuery-UI along with the .draggable() method. My current HTML structur ...

Including an image side by side with clickable text within a list

Check out my progress here: http://jsfiddle.net/dDK6z/ I've experimented with using display:inline(-block), as well as adjusting margins, padding, and more, but I can't seem to get the image to move down or the text to move up. Does anyone have ...

What is the process for integrating a personalized font into the <head> section of the ConvertTo-HTML?

I created a script to generate an HTML file containing information about the services on a computer, along with some additional styling. $a = "<style>" $a = $a + "BODY{background-color:peachpuff;}" $a = $a + "TABLE{border-width: 1px;border-style: so ...

Refresh a row in real-time by utilizing a modal with JavaScript or jQuery

Is there a way to dynamically edit and update a previously submitted row (category name) in a table? I am able to edit a row by clicking on an edit button and displaying a modal with the current value. However, I am facing a challenge when trying to submit ...

Utilizing the HTML5 Pattern Attribute in Conjunction with Websockets

Being completely new to web programming, I am struggling to understand why the pattern attribute in the text field below is not validating properly due to my javascript. <form id="aForm"> <input type="text" pattern="^[ a-zA-Z0-9,#.-]+$" id="a ...

What is the best way to align a card-body to the right for screen sizes larger than 1280 using Bootstrap

I'm having trouble getting the float classes to work on my Bootstrap cards. Specifically, I want to float a card-img left and the card-body right using Bootstrap cards, but it's not behaving as expected. Can someone provide some insight into what ...

Incorporating information into Observable in Angular 2

I'm currently working on loading gifs from the API based on a search parameter in batches of 20. Once I reach the bottom of the page, I need to load another 20. To achieve this, I've implemented observables. However, I'm facing an issue with ...