Jump to content

Limit Date/Time Picker to future


saschapi
 Share

Recommended Posts

Hi guys,

I added a date-time field to a template that will initiate some scheduled stuff by a cron.

However I would like to check if the date and time the editor has chosen is in the future (in fact it should be at least 30min into the future). And through out a validation error if the date/time is not valid in this way.

Any help how to hook into the validation process? Or is there a way to limit the date picker in this way in advance, before the page would be saved?

Cheers and thanks for any input

Sascha

Link to comment
Share on other sites

You can add your own validation with a small hook in site/ready.php.

wire()->addHookAfter("InputfieldDatetime::processInput", null, "validateFuture");

function validateFuture(HookEvent $event) {
    $field = $event->object;
    
    // Make sure to enter the correct name of your field here:
    if($field->name == "crondate") {
    	// Compare field with current time plus 30s * 1000ms:
    	if($field->value < time() + 30000) {
    		$field->error("Date is not in the future!");
    	}
	}
}

Adapting the datetimepicker isn't easy if possible at all.

  • Like 3
Link to comment
Share on other sites

You might want to also validate the date when the page is saved as @BitPoet suggests, but it is possible to limit the datepicker to only future dates with some custom admin JS. The relevant option is minDate. The core sets the datepicker options on focus, so to ensure the custom option doesn't get overwritten I've found that the most reliable way to apply it is by using a beforeShow function.

For a Datetime field named "crondate":

$(function() {
	$('#Inputfield_crondate').on('focus', function() {
		$(this).datepicker('option', 'beforeShow', function() {
			return { minDate: 0 };
		});
	});
});

2020-01-17_094946.png.3c5e6fa50191ee04212f0ed07f75779a.png

 

Edit: just noticed you want a minimum time also.

Try this:

$(function() {
	$('#Inputfield_crondate').on('focus', function() {
		$(this).datepicker('option', 'beforeShow', function() {
			return {
				minDate: 0,
				minDateTime: new Date(new Date().getTime() + 30 * 60000)
			};
		});
	});
});

2020-01-17_100539.png.ed348856b99adb695ff91fa94eeffb67.png

Edited by Robin S
Added minDateTime option
  • Like 5
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...