Jump to content

Validate input entered into datetime fields


Robin S
 Share

Recommended Posts

I was surprised to discover recently that a datetime inputfield using the jQuery UI datepicker will accept any old nonsense that an editor might put into it, allowing the page to be saved and often converting the input into strange unwanted values without warning. More info: https://github.com/processwire/processwire-issues/issues/1138

I think the core should be validating the input, but in the meantime here is some code that will check the input against the configured format (date only - I haven't tried time settings) and alert the user if the value is invalid. In the case of invalid input the previous value is restored.

In /site/ready.php:

// Datetime fields: load Vex to use for invalid date alerts
$wire->addHookAfter("InputfieldDatetime::renderReadyHook", function(HookEvent $event) {
	$this->wire('modules')->get('JqueryUI')->use('vex');
});

In custom admin JS (loaded however you like - I use AdminOnSteroids)

// Validate datetime inputfields
$(document).on('focus', '.InputfieldDatetime input', function() {
	$(this).data('prev-value', $(this).val());
});
$(document).on('blur', '.InputfieldDatetime input', function() {
	var format = $(this).data('dateformat');
	try {
		$.datepicker.parseDate(format, $(this).val());
	}
	catch(e) {
		$(this).val($(this).data('prev-value'));
		var example_date = $.datepicker.formatDate(format, new Date('23 Oct 2014'));
		vex.dialog.alert('The date you entered is not in the valid format. Example of format: ' + example_date);
	}
});

Result:

date.gif.67535e4fbcf3c99ca524e130364281f8.gif

  • Like 4
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...