New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
limit DATE fields in Elementor Forms #6372
Comments
Well first you should set the server side validation: // Validate the date field min value to 7 days ago and max value to 7 days from today.
add_action( 'elementor_pro/forms/validation/date', function( $field, $record, $ajax_handler ) {
// make sure ts the correct date field
if ( 'YOUR_FIELD_ID' === $field['id'] ) {
return;
}
$min_allowed_date = strtotime( '-7 day' );
$max_allowed_date = strtotime( '+7 day' );
$form_date = strtotime( $field['value'] );
if ( $min_allowed_date > $form_date ) {
$ajax_handler->add_error( $field['id'], 'The Minimum allowed date is, ' . date( 'Y-M-d', $min_allowed_date ) );
}
if ( $max_allowed_date < $form_date ) {
$ajax_handler->add_error( $field['id'], 'The Maximum allowed date is, ' . date( 'Y-M-d', $max_allowed_date ) );
}
}, 10, 3 ); look closly at these lines: $min_allowed_date = strtotime( '-7 day' );
$max_allowed_date = strtotime( '+7 day' ); in this example we validate the the date must be between 7 days ago and 7 days from today, but you can easly change that to anything else. And as for the JavaScript date picker (flatpickr) here is a little Helper I wrote: var limitFlatPicker = limitFlatPicker || {};
jQuery( document ).ready( function( $ ){
limitFlatPicker = {
defaultSettings: {
selector: '.flatpickr-input',
minDate: false,
maxDate: false,
},
settings: {},
init: function( options ) {
this.settings = $.extend( this.defaultSettings, options );
if ( this.settings.minDate || this.settings.maxDate ) {
this.waitForFlatpicker( this.callback );
}
},
waitForFlatpicker: function( callback ) {
if ( typeof window.flatpickr !== 'function' ) {
setTimeout( function() { limitFlatPicker.waitForFlatpicker( callback ) }, 100 );
}
callback();
},
modifyPicker: function( picker, settings ) {
flatpickr( picker ).set( settings );
},
callback: function() {
var self = limitFlatPicker;
$( self.settings.selector ).each( function() {
var picker = $( this )[0],
pickerSettings = {};
if ( self.settings.minDate ) {
pickerSettings['minDate'] = self.settings.minDate;
}
if ( self.settings.maxDate ) {
pickerSettings['maxDate'] = self.settings.maxDate;
}
self.modifyPicker( picker, pickerSettings );
} );
}
}
} ); and to use it you simple call it with the dates you want: var aWeekAgo = new Date(),
aWeekFromToday = new Date();
aWeekAgo.setDate( aWeekAgo.getDate() - 7 );
aWeekFromToday.setDate( aWeekFromToday.getDate() + 7 );
limitFlatPicker.init( {
minDate: aWeekAgo,
maxDate: aWeekFromToday
} ); Just make sure you enclude the JS on the correct page, could be easly done via your functions.php add_action( 'wp_footer', function() {
if ( ! is_page( YOUR_PAGE_ID_HERE ) ) {
return;
}
?>
<script>//JS CODE HERE</script>
<?php
} ); Good luck. |
Hi |
Would LOVE this feature non-coded. Currently using 4 extra plugins: CF7, CF7DB (for collecting csv data), Column Shortcodes( to make fields side-by-side), and Contact Form 7 Shortcode Enabler (for integration of previous) for the stupid calendar restriction. Thanks for the code. Gonna try it someday. |
Hello,
|
How can I use localization with the example you wrote? Then adding |
where i write this code? Location?! |
Tried to edit in Childtheme -> Functions.php What i need to replace??? |
All the JS code can go into where I wrote |
Forgive me for being obtuse. I am using Elementor Pro (precisely because I am not a backend developer. So all this code-speak is confusing without hand holding for this noob.) Would you kindly explain for me what parts of the above JavaScript can be used in the Elementor Page itself using the HTML widget? And, which part I must use with a Header/Footer code-injection plugin. **How would you write the code to reflect this scenario: (and precisely, where does each part go) Form Element Date picker 1. Form Element Date Picker 2. This is used in a Guest Pass form where it will be issued up to no more than 21 days total. Even though it says "Maximum 21 Days", people still put in whatever dates they want and I have to manually correct the submission...grrrr. ((The thing I don't understand with the Elementor Date Picker widget is why would you have a min/max date that you have to pick on the calendar instead of this +/- date parameter so it can be evergreen, like what I am looking for.)) Thank you in advance for your help! |
Hi @dasignlady
This will ensure we are validating the date field on the server side: Now we need to take care of the front-end validation and create better UX (User experience).
This will essentially limit the datepicker to dates from "today" to "21 days from today" If for some reason this doesn't work you can change the number Enjoy! |
@odedta Wow! Thank you so much for your fast and detailed reply!!! |
Hi @odedta or @bainternet I need a code to define previous date date (today) My business offers cleaning services. Please tell me where I put the code please :) Thanks in advance |
Hi @maisnovo |
Thanks @odedta. Unfortunately dont work for me Past the code on functions.php and jquery on footer widget |
PM on Facebook, i'll try to help when I can. |
Hi! |
I think the condition to validate the correct date field should be as follow:
|
This seems unnecessarily complicated when it should be added to the core functionality of Elementor. Most people use the date field to either pick something only in the future or only in the past or within a certain period so it should be part of Elementor. Otherwise, it's mostly useless |
I just figured this out and I thought it would be useful for everyone because I haven't managed to find an easy solution other than adding PHP code to the functions.php. By default it's not possible to set limits or formatting to the date form fields. There is a small library called Flatpickr.js that can help with this. You are using a theme that doesn't load Flatpick.js automatically:
You can also add the HTML code right after any form your want to target so that it doesn't run on every page. You are using the Hello theme:
You then need to replace the FIELD_ID with your own ID and the 4th line with all the custom parameters you can find on Flatpick.js's website: https://flatpickr.js.org/examples/ The code is wrapped in a DOMContentLoaded event because the Hello theme runs the library from the footer so the code won't be able to run before it has been loaded. So far this is the simplest method I have found. I hope it helped you. |
Thanks! This is brilliant. But I think I'm experiencing a bug. The first second of loading my page it does work with both mode and minDate. But after one second the datepicker kind of reloads and the script won't work. I'm using the Hello Theme also. |
Hi @alexplex That's strange. Try to create a new page with nothing else on it, just a form, and then try again. Also look at the Console to see if you are getting any error related to Flatpickr.js |
@ashkan-ahmadi Same on a new test page. I'm not getting any error in the console. It almost feels like it loads everything correctly the first second but then a second later something else loads, perhaps in the footer, and resets the script. Here you can have a look at the source code if you want :) Tried to deactivate all plugins. Nothing. |
That's strange. Try changing the theme and loading the library before the form and then DOMContentLoaded event after the form. I just reviewed the code, it's most probably the script from line 248 to 254 doing this resetting this after 1 second. I'm not how that was added though because I don't have this on my own pages. If you added that, delete it. |
Yes. You can see everything you can do here: https://flatpickr.js.org/examples/ (Disabling dates by a function) |
Thank you, this is literally the only code on this thread that worked |
complete code including blocked weekends! <script>jQuery( document ).ready( function( $ ) {
setTimeout(
function() {
let plusFourDays = new Date();
let eightTeenDaysFromToday = new Date();
plusFourDays.setDate( plusFourDays.getDate() + 4 );
eightTeenDaysFromToday.setDate( eightTeenDaysFromToday.getDate() + 18 );
let options = {
minDate: plusFourDays,
disable: [
function( date ) {
return ( date.getDay() === 0 || date.getDay() === 6 );
}
],
locale: { "firstDayOfWeek": 1 },
maxDate: eightTeenDaysFromToday,
};
flatpickr( "#form-field-YOUR_ID", options );
},
500
);
} );
</script> |
can i have a code to just disable past dates only , code i can put in elementor code section in the DATE FIELD how do i set min date to 0 - it is not allowing me to set to 0 so that past dates can be disable your help is much appreciated - i am using elementor pro as well |
Apparently, something in Elementor has changed and now if you are using the code I added last year does not work. For some reason (would be cool if someone has the patience to figure out why), the Flatpickr library finishes loading after DOMContentLoaded. A quick fix is to add the flatpickr function inside a setTimeout() function with a 500ms (or 1000ms) delay. For example:
|
@immu2018 No, you can't use the Code widget. That's not for running a code, that's for displaying a code (like how you see the code below). You need to use the HTML widget. To make the previous dates disabled, you need to copy-paste the following code in an HTML widget on the same page as your form (below it would be best). The
|
i would like to thank you and appreciate you for the fast reply you have given to my issue - i hope you progress in your life and career |
@ashkan-ahmadi |
Hi @namazty
Here are the params you can modify in the code:
Remember: you can see all the examples here: https://flatpickr.js.org/examples/ (you can mix and match anything you need) |
Why is this closed? We don't get elementor pro to use code. |
Hey, I tested this and it worked for me on Elementor 3.5.6. e.g., what I would like to get the following with 2 datepicker entries FROM_DATE = > (today + 5 days) In English that would mean booking only allowed from 5 days from today and minimum stay is 7 days. |
Thank you for this code. I did exactly what you mention. As in putting the HTML code after the form. I do need some help. How do I tell flatpickr is workiong? My form doesn't seem to start on Monday and the Saturdays are not grey out. From the breakpoint, I do know the setTimeout is being triggered but nothing seems to be working. |
Hi @samwzirong. The most common reason is not adding the right field ID. If your page is live, share the link and i will check it. If not, simply write the ID of the date field and I will give you the exact code to copy-paste |
Hi @ashkan-ahmadi thank you! Oh wait it's working! I was about to send you the link and noticed it's working now. Most likely it's a cache issue. |
Hey! I did everything as you explained and nothing happened! this is the code i wrote in the end of functions.php file
}, 10, 3 ); add_action( 'wp_footer', function() {
} ); limitFlatPicker.init( { |
That's perfect, Thanks. Any idea how to html for Elementor for tel filed to accept only numbers and 8 digit? |
The Flatpickr library is only for dates and times. You cannot do that with this library. Elementor cannot do that either. You need to add the pattern attribute to the element using JS. Paste this code in a Custom HTML widget AFTER the form that has the tel input and replace FIELD_ID with the id of your tel input field. <script>
const tel = document.querySelector('#form-field-FIELD_ID')
tel.setAttribute('pattern', '[0-9]*\d{8,8}')
</script> |
Thanks, I should try that magic and update you. Appreciated your fully support. |
@ashkan-ahmadi Can you help me to make the minimum date on this form to be 5 days from today? I cannot get it to work: https://bunsbakery.co.za/custom-order/ |
@doggopress Yeah that's easy. You need to set |
Thank you @ashkan-ahmadi it worked for me! Now my only problem is that it does not work on mobile. Can you assist with this? |
i myself think the best way to do is to use this simple JS to achieve min or max date, first use either elementor pro's custom code feature or a plugin like header footer script and past this code |
Elementor gives the option to select "Native HTML5" for the datepicker (same for time picker btw.) In my case, I would like the datepicker to have a minimum date of today. Right after the form you have created, add a HTML widget and pass following code to it:
I hope this helps. You should also have some server-side validation as mentioned in previous comments. |
Instructions:
Hope it helps. |
Looking forward to have this implemented without the need of coding very soon in Elementor. Thank you @Ozman-Minhas for the solution provided |
nice finding, thanks @Ozman-Minhas . using in html code widget beneath the form:
outputs the desired result and works... BUT: unfortunately changes the default language from german back into english! anybody any clue why? |
I am not a programmer by any mean, but the information here might help you:
https://flatpickr.js.org/localization/
Remember that your friend in need of a website *THAT WORKS*, will thank you
for referring him/her to us.
Oscar
Centrix Corp. = websites THAT WORK for you *and everyone*!
Work: 785-CENTRIX (785-236-8749)
M: 919-66OSCAR (919-666-7227)
***@***.***
centrix.com
<http://calendar.centrix.com/>
…On Fri, Nov 24, 2023 at 1:09 PM dasigna ***@***.***> wrote:
<script>
window.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
flatpickr("#form-field-YOUR-FIELD-ID", {
mode: "range",
altInput: true,
altFormat: "F j, Y",
dateFormat: "Y-m-d",
minDate: new Date().fp_incr(1),
maxDate: new Date().fp_incr(21)
});
}, 500)
});
</script>
Instructions: 1- Drage and drop the HTML widget on the page (preferably at
the bottom of the page) where you have this form and copy and paste the
above-mentioned code. 2- Change YOUR-FIELD-ID with the ID of date field in
your form. 3- If you want to change the date range, change the numbers in
the following code:
minDate: new Date().fp_incr(1),
maxDate: new Date().fp_incr(21)
Remember: You can get more examples here: https://flatpickr.js.org/examples/
Hope it helps.
nice finding, thanks @Ozman-Minhas <https://github.com/Ozman-Minhas> .
nevertheless i discovered a little glitch when fiddling around actually...
using in html code widget beneath the form:
window.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
flatpickr("#form-field-XXX", {
altFormat: "l, d. F Y",
dateFormat: "l, d. F Y",
minDate: new Date().fp_incr(1),
maxDate: new Date().fp_incr(100),
"disable": [
function(date) {
// return true to disable
return (date.getDay() === 1 || date.getDay() === 2);
}],
locale: {
firstDayOfWeek: 1 // start week on Monday
}
});
}, 500)
});
</script>```
outputs the desired result and works... BUT: unfortunately changes the default language from german back into english!
this means that the datepicker as well as the date output suddenly reverses back from de to en.
anybody any clue why?
—
Reply to this email directly, view it on GitHub
<#6372 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AKIERAO364XJZWMCPNIHG3TYGDPD3AVCNFSM4GJBOBWKU5DIOJSWCZC7NNSXTN2JONZXKZKDN5WW2ZLOOQ5TCOBSGU4TOMBUGIYQ>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
@oscarhenao - thanks, the localisation options are known - but: first thing: the form as well as the flatpickr UI etc. is in the right language (german) natively. injecting this script changes everything to english including the field output. second: already had the idea to tweak something within the script to revert the language back to german - but cant get it to work in no way... sadly. had a few hopes someone here has more knowledge about this thing and might help out or might be able to explain whats happening here. so basically: sincere greetings. |
Hi there! |
Check this:
https://flatpickr.js.org/examples/#datetimepicker-with-limited-time-range
Remember that your friend in need of a website *THAT WORKS*, will thank you
for referring him/her to us.
Oscar
Centrix Corp. = websites THAT WORK for you *and everyone*!
Work: 785-CENTRIX (785-236-8749)
M: 919-66OSCAR (919-666-7227)
***@***.***
centrix.com
<http://calendar.centrix.com/>
…On Thu, Dec 14, 2023 at 1:45 PM rizbaig ***@***.***> wrote:
Hi there!
I have an elementor form with time field, I have to make range selection
between 10am to 4pm only for clients, can anyone help me to do so?
Thanks
—
Reply to this email directly, view it on GitHub
<#6372 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AKIERAKK6TR6WFXOBB3T5DLYJNCMBAVCNFSM4GJBOBWKU5DIOJSWCZC7NNSXTN2JONZXKZKDN5WW2ZLOOQ5TCOBVGYZTSNZUGQ3Q>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
Prerequisites
What problem is your feature request going to solve? Please describe.
An option to limit a DATE field in Elementor Forms so the user will not be able to enter a date younger than X (parameter) days after today.
i.e. if today is December 20th, user will be able to choose dates from December 27th and so on until the end of time...
Describe the solution you'd like
a place to choose the type of the limit (max/min), and a specific date, or number of days from today (which is fluid).
Describe alternatives you've considered
A ready made JS code?
Additional context
The text was updated successfully, but these errors were encountered: