I've been searching similar questions, but I am having a hard time relating my setup with what I see in other questions. Maybe I am having a fundamental misunderstanding of the JQuery validation plugin, but either way I need some guidance why my code is not working.
Overview
I have a form that I want to be checked if valid before I display a modal (i.e. "Are you sure?") where the user can submit the form. I don't want to check if the form is valid during the submitHandler because then that means if there is an error I will need to hide the modal for the user to fix validation before displaying the modal again.
Code Setup
I followed this one jQuery validation tutorial that seemed logical to me where all your forms' validation is stored in one .js file. This file holds my validator.setDefaults, multiple validator.addMethod, and the individual forms' .validate() method including the rules, messages, etc. All these methods are wrapped in a $("body").on("click", function () {} event handler to trigger the validate. Here is that .js file in pseudo including the specific form.validate:
$("body").on("click", function () {
/*
Function to handle validation for all forms.
*/
[...all of my setDefaults.....]
[...all of my $.validator.addMethods......]
[...all my $(form).validate() methods.....]
$("form.update-circuit").validate({
rules: {
Site: {
required: true,
autocompleteSelection: true,
},
WorkOrder: {
validWorkOrder: true,
},
},
messages: {
Site: {
required: "Please choose the Station.",
autocompleteSelection: "Please choose from the list.",
},
WorkOrder: {
validWorkOrder:
"Please enter a valid Work Order.<li>5 alphanumeric\
characters only.</li>",
},
},
onfocusout: function (element) {
$(element).valid()
},
})
})
In another .js file, I handle the rest of my webpage's javascript. This is where I am checking the condition if the form is valid and displaying the modal. Right now, I receive a jquery.validate error "Uncaught TypeError: Cannot read properties of undefined (reading 'type')".Below is the function:
$(document).on(
"click",
"form.update-circuit button.update-circuit",
function (e) {
/*
Event Handler: Check validation before showing the Update Modal.
*/
e.preventDefault()
var formElement = $(this).closest("form")
var updateModal = $($(this).data("bs-target"))
if (formElement.valid()) {
$(updateModal).modal("show")
}
},
)
Question
So why is $(form).valid() not working? Does my $(form).validate() not fire prior to the .valid() method? Do I have to call .validate() again in my separate .js file?