Consider breaking this down into separate steps. The form submission is the final step in the process, after all conditions are satisfied.
- User fills out form
- We validate the form
- 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.