Submit blocking by comparing filed dates in form

By: Christopher Sticky | Asked: 07/10/2023
ForumsCategory: How-toSubmit blocking by comparing filed dates in form
Christopher Sticky asked 1 year ago

I have a form with two date selectors, start and end date. I have a hidden field that contains a user meta generated date. i would like to block submission and generate an error message if either of the dates is on or later than the user meta generated date. I have a script that i have been trying but with no success. As an FYI I have also had minimal success with user meta content in fields. Is this possible?

jQuery(document).ready(function($) {
// The CSS classes of the two date fields
var dateField1 = $('#field_cxq7o');
var dateField2 = $('#field_fo9mi');

// The field key of the user meta date field
var blockedDateField = $('.frm_field[data-key="la1dv"]');

// Handler to the form's submit event
$('.frm_form').on('submit', function(e) {
// Get the selected dates from both fields
var selectedDate1 = new Date(dateField1.val());
var selectedDate2 = new Date(dateField2.val());

// Get the blocked date
var blockedDate = new Date(blockedDateField.val());

// Perform the date comparisons and block submission if necessary
if (selectedDate1 >= blockedDate || selectedDate2 >= blockedDate) {
e.preventDefault(); // Prevent form submission
alert('Submission blocked: one of the selected dates is on or after the restricted date.'); // Error message
}
});
});

1 Answers
Victor Font answered 1 year ago
There's a few suspect areas in your code. First, where are you finding an element named data-key in this line: $('.frm_field[data-key="la1dv"]'); There is no data element named data-key in any Formidable generated code unless you added it to your target field on the form's Customize HTML page. And a data property would be associated with the actual element, not a class in a parent div. Why are you targeting classes when you need the field values? The .frm_field class is in the wrapper div for the element. You're not getting that when you create objects from the fields themselves.
Victor Font replied 1 year ago

Next, why are you creating field objects instead of just getting the values? Your first two lines should be:

var dateField1 = $('#field_cxq7o').val(),
dateField2 = $('#field_fo9mi').val(),
blockedDateField = $('#field_la1dv').val();

You don't need any of the code instantiating new data fields.

Last, you should not be using the submit event to validate a field. You should be using https://formidableforms.com/knowledgebase/frm_validate_field_entry/ as the hook.

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right