Creating validation for Materialize CSS modals

Utilizing Materialize CSS for my post design, I have a form in a modal that I need to submit to the server. Within this form, one of the checks involves verifying if all fields contain a value.

<form>
            <div class="input-field">
                <input type="text" id="title"  class="validate" required="" aria-required="true">
                <label for="title">Title</label>
            </div>

Although the title field is set as required, upon clicking the submit button in the modal, it closes even when the title field is empty. Is there a method to prevent the modal from closing upon validation error in Materialize CSS v1?

Answer №1

Consider breaking this down into separate steps. The form submission is the final step in the process, after all conditions are satisfied.

  1. User fills out form
  2. We validate the form
  3. We provide feedback to the user

Depending on the outcome of step 2, we may either loop back to step 1 or proceed to step 3.

Modal Layout:

  <div id="modal2" class="modal-container">
    <div class="modal-box">
      <div class="input-section">
         <input type="text" id="user-input"  class="validate-field" required="" aria-required="true">
         <label for="user-input">User Input</label>
         <span class="feedback-text" data-error="Please provide valid input" data-success="Thank you!"></span>
        </div>
    </div>
    <div class="modal-footer">
      <a id="submit-form-button" href="#!" class="btn-submit"&rt;Submit</a>
      <a href="#!" class="close-modal btn waves-effect waves-red red">Close</a>
    </div>
  </div>

We include an optional feedback-text span for providing user feedback, following the directives in the guidelines.

JavaScript Implementation:

document.addEventListener('DOMContentLoaded', function() {
    
    // initialize modal
    var elements = document.querySelectorAll('.modal-container');
    var instances = M.Modal.init(elements);
  
    // obtain submit button
    var submitButton = document.querySelector('#submit-form-button');
  
    // Execute custom function upon button click
    submitButton.addEventListener("click", performValidation);
  
    // Function validates user input
  
    function performValidation() {
      var userInputField = document.querySelector('#user-input');
      
      if(userInputField.value) {
        
        // carry out form submission
        
        // apply 'valid' class to display feedback
        userInputField.classList.add('valid-feedback');
        // close the modal
        instances[0].close();
        // reset form
        userInputField.value = '';
        // remove 'valid' class
        userInputField.classList.remove('valid-feedback');
      } else {
        // request input from user
         userInputField.classList.add('invalid-feedback');
      }
    }
  
  
  });

We retrieve the value entered in the text field and based on that, assign a valid-feedback or invalid-feedback class - this utilizes materialize functionality to hide or display the appropriate message set in data-error and data-success.

The only additional step needed here is the actual form submission - something along the lines of form.submit().

Link to Codepen.

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

Challenges with Customizing WooCommerce Design

Looking for some assistance with this issue that's been driving me crazy. I have successfully set up WooCommerce on a test site using the default TwentyThirteen theme and everything is working perfectly. However, when I try to implement it on a custo ...

Button with CSS accordion menu

Seeking assistance as I am new to web design and experiencing an issue with my accordion button. I am trying to implement an animation that will display my <ul> when clicking within the .container element. The animation works fine, but I am having tr ...

Styling Images Inside a DIV Container Using CSS Float

Considering that I have 2 divs with images and text, I encountered some formatting issues when attempting to float the image to the left using float:left;. The strange formatting is ruining the layout. Below, I've included my code snippet along with a ...

Finding the height of concealed content within a div using the overflow:hidden setup

I'm trying to create a div that expands when clicked to reveal its content. I've taken the following steps so far: Established a div with overflow:hidden property Developed a JavaScript function that switches between a "minimized" and "maximize ...

Can someone assist me in figuring out why the ShowDetail.html page is not opening after I submit my form?

I'm having trouble getting the shoDetail.html page to open when I submit the code. I even tried entering the complete URL, but it still won't work. Here is the code I am using: <div class="form-group row"> <div class="col-lg-12 col-md-1 ...

Internet Explorer 8 is causing alignment problems with sidebars on certain websites within a Wordpress multisite setup

I am managing a Wordpress multisite setup with the following websites: The main portal: which connects to The issue arises on all pages of gprgebouw.nl and gpradvies.nl but not on the other domains. Attached is a screenshot of the homepage of gprgebouw. ...

Card columns with dropdown extending into adjacent column

Encountering a strange problem with the card-columns layout in Bootstrap when using dropdown menus within the cards. The issue arises when the dropdown-menu divs of the lower cards bleed into the next column, despite appearing in the correct position. Thi ...

Minimizing the amount of code written

I have the following CSS code: /* unvisited link */ a.underl:link { color: #000000; text-decoration: none; } /* visited link */ a.underl:visited { color: #000000; text-decoration: none; } /* mouse over link */ a.underl:hover { color: ...

Utilizing the CSS transform scale() function to enlarge an element while preserving its entire content and allowing for scrolling

Check out this live example: https://jsfiddle.net/b8vLg0ny/ You can actually utilize the CSS functions scale and translate to magnify an element. For instance, consider a scenario with 4 boxes arranged in a 2x2 grid. The HTML code for this setup is as f ...

Utilizing CSS3 Animation for enhanced hover effects

I have a setup with two divs. One of the divs expands in height when I hover over it. What I'm trying to achieve is to display text with a fade-in effect somewhere on the screen when I hover over that specific div. Additionally, I want to show another ...

Ensure that the Bootstrap 5 modal and backdrop are sized to fit the parent container's width and height rather than filling the entire screen

Is there a way to limit the size of a Bootstrap 5 modal dialog and backdrop? The example below occupies 100% of the screen, can it be adjusted to cover only the parent main container? <main class="container-fluid pt-4 px-4" style="height ...

Adjust the page height when switching between two divs

Currently, I have two divs that are being displayed one at a time using the toggle method. Please refer to the screenshot below: In the image provided, when the user clicks on "show more", the div will toggle based on the first item in the list. If the u ...

What method can be used to eliminate the shadow of a container when rotating a div?

I am currently working on creating a dynamic card that expands and reveals additional information upon mouse rollover. The challenge I am facing is that the shadow effect remains visible when flipping the card, which disrupts the overall desired effect. H ...

Customize your Bootstrap navbar with a specific width and perfectly centered position

Using Bootstrap 4, I aim to customize the inline form in the navbar to have a specific width on laptops and extend to the full screen on mobile devices. Here is how it appears on my mobile device: https://i.sstatic.net/gjewu.png https://i.sstatic.net/KJh ...

How to modify hyperlink text color in Bootstrap 4 navbar

Below is the code snippet that controls the navigation bar on the website: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" hr ...

How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way: <h1 [ngStyle]="{'background-color': backgroundColor}" The component named HelloComponent employs the O ...

Out of nowhere, Div became completely unresponsive

As part of my lesson plan on jQuery, I wanted to demonstrate a sliding effect using a div element. Initially, the sliding worked fine when clicked, but then I tried adding code for hiding another element and encountered issues. Even after removing the new ...

Managing the css @print feature within the WordPress admin interface

When attempting to use 'window.print()' to print only a specific div inside the WordPress admin area, I tried enqueueing CSS to load on the desired page and hide all elements except for the target div. However, the issue arises when the text form ...

Choose a div using jQuery and activate a hidden div

Seeking assistance in creating an interactive infobox that appears when hovering over a related image. Currently, the infobox pops out and flashes, but there is a problem where it shifts away from the image during the hover. I attempted to only display th ...

Support for numeric font weights in web browsers

Which browser versions have full support for using numeric values for the font-weight property? This includes Internet Explorer, Firefox, Chrome, Safari, iOS Safari, and Android Browser. While most browsers support the keyword values 'bold' and ...