Kendo DateTimePicker format HHmm - asp.net-mvc

I have a kendo datetimepicker control and when a user manually types in an incorrect format missing the colon in the time, the validation does not catch this and in the MVC controller, the models property has a null date/time.
My client side validation is able to parse 21/01/2015 1230 but by the time it reaches the model in the controller server side its null, as it cannot map and parse the datetime.
Some console.log output of the value input and kendo.parseDate's effort.
21/01/2015 0000
Wed Jan 21 2015 00:00:00 GMT+0000 (GMT Standard Time)
Here's my client-side validation below.
So how can I force the validation to work client-side?
$("#accidentForm").kendoValidator({
rules: {
date: function (input) {
if (input.is("[name=Accident.IncidentDate]")) {
console.log(input.val());
var d = kendo.parseDate(input.val());
console.log(d);
return d instanceof Date;
}
return true;
}
},
messages: {
customRuleDateTimePick: "Incident date time format incorrect."
}
});
// attach a validator to the container and get a reference
var validatable = $("#accidentForm").kendoValidator().data("kendoValidator");
$("#btnSave").click(function () {
//validate the input elements and check if there are any errors
if (validatable.validate() === false) {
// get the errors and write them out to the "errors" html container
var errors = validatable.errors();
$(errors).each(function () {
$("#errors").html(this);
});
return false;
}
return true;
});

OK specifying a format and culture parameter on the kendo.parseDate seems to help and stops the post to the server until a valid date AND time is input.
$("#accidentForm").kendoValidator({
rules: {
date: function (input) {
if (input.is("[name=Accident.IncidentDate]")) {
var d = kendo.parseDate(input.val(), ["dd/MM/yyyy HH:mm"], 'en-GB');
return d instanceof Date;
}
return true;
}
},
messages: {
date: "Incident date time format incorrect."
}
});
Another alternative, simpler I think, was to extend the validator methods for date types. This then picked up the MVC error message attributes, so I get to use the right resource.resx file rather than hard code my error text.
<script type="text/javascript">
$(function () {
$.validator.methods.date = function (value, element) {
// Custom validation required for DateTimePicker, so use kendo.parseDate as it works better than jquery unobtrusive validation.
return this.optional(element) || kendo.parseDate(value, ["dd/MM/yyyy HH:mm"], 'en-GB') !== null;
}
});
</script>

Related

how to reject the selected date in onSelect in jquery ui DatePicker

I have a web-form where I'm asking the user for several dates. Usually, but not always, a repeated date will be a human error. So in the onSelect function I'm checking to see if the date has already been entered, and asking the user to confirm whether a duplicated date was intentional. If the user says No, how to clear the date value from the picker?
// datesList initialized in outer scope
onSelect: function (thedate, picker) {
if ($.inArray(new Date(thedate).valueOf(), datesList) == -1) {
//store chosen dates in datesList if we haven't seen it before
datesList.push(new Date(thedate).valueOf())
} else {
// ask the user if it was intentional
//if unintentional, reject the choice and clear the picker
}
}
Not sure you can do it with given options, but you could override _selectDate and add a condition. Something like this:
$.datepicker._selectDate = function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input)
inst.input.val(dateStr);
this._updateAlternate(inst);
var onSelect = this._get(inst, 'onSelect');
if (onSelect){
// you get the value of onSelect
var shouldHide = onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input && shouldHide){
inst.input.trigger('change'); // fire the change event
}
if (inst.inline)
this._updateDatepicker(inst);
// If onSelect return false, you don't hide the datepicker
else if (shouldHide) {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) != 'object')
inst.input.focus(); // restore focus
this._lastInput = null;
}
}
$('input').datepicker({
onSelect: function(e, ui) {
if (confirm('OK?')) {
return true;
} else {
this.value = "";
return false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"></link>
<input type=text></input>

AngularJS: Creating a directive for converting a string to a Date on the fly

Angular UI Bootstrap changed the way of what the datepicker expects as ng-model in some version after 1.13.0. Before it was fine to give it an ISO date string, now it wants a Date object.
I consume ISO date strings from my API though, so I have to
convert them into Date objects before giving it to the datepicker and
convert them back to an ISO date string when storing it.
In the past I used a directive like this:
function DateObjectDirective() {
const directive = {
restrict: "A",
require: ["ngModel"],
link(scope, element, attributes, controllers) {
const ngModel = controllers[0];
ngModel.$formatters.unshift(value => {
let output = null;
if(value) {
output = moment(value).toDate();
}
return output;
});
ngModel.$parsers.unshift(value => {
let output = null;
if(value) {
output = moment(value).format();
}
return output;
});
},
};
return directive;
}
This no longer works though, as the following error is reported:
this.activeDate.getFullYear is not a function
My guess is that the datepicker still uses the string as reference. Is there any other way I can convert before giving my data to the datepicker?
I found out that the directive I posted does indeed still work. The only problem was the order in which AngularJS evaluated the directives.
For example:
<input ng-model="someDateString" uib-datepicker-popup="yyyy-MM-dd" woo-date-object>
In my case, woo-date-object was always evaluated before uib-datepicker-popup. The result was that the datepicker has always pushed its own formatter on top of ngModel.$formatters, thus eliminating the possibility for me to intervene.
The solution is to give the own directive a higher priority. UI's datepicker doesn't have one set, so anything above 0 (which is the default) works:
{
restrict: "A",
require: "ngModel",
priority: 9999,
link(scope, element, attributes, ngModel) {
ngModel.$formatters.push(value => {
let output = new Date();
if(value) { output = moment(value).toDate(); }
return output;
});
ngModel.$parsers.push(value => {
let output = null;
if(value) { output = moment(value).format(); }
return output;
});
},
}

Full-featured autocomplete widget for Dojo

As of now (Dojo 1.9.2) I haven't been able to find a Dojo autocomplete widget that would satisfy all of the following (typical) requirements:
Only executes a query to the server when a predefined number of characters have been entered (without this, big datasets should not be queried)
Does not require a full REST service on the server, only a URL which can be parametrized with a search term and simply returns JSON objects containing an ID and a label to display (so the data-query to the database can be limited just to the required data fields, not loading full data-entities and use only one field thereafter)
Has a configurable time-delay between the key-releases and the start of the server-query (without this excessive number of queries are fired against the server)
Capable of recognizing when there is no need for a new server-query (since the previously executed query is more generic than the current one would be).
Dropdown-stlye (has GUI elements indicating that this is a selector field)
I have created a draft solution (see below), please advise if you have a simpler, better solution to the above requirements with Dojo > 1.9.
The AutoComplete widget as a Dojo AMD module (placed into /gefc/dijit/AutoComplete.js according to AMD rules):
//
// AutoComplete style widget which works together with an ItemFileReadStore
//
// It will re-query the server whenever necessary.
//
define([
"dojo/_base/declare",
"dijit/form/FilteringSelect"
],
function(declare, _FilteringSelect) {
return declare(
[_FilteringSelect], {
// minimum number of input characters to trigger search
minKeyCount: 2,
// the term for which we have queried the server for the last time
lastServerQueryTerm: null,
// The query URL which will be set on the store when a server query
// is needed
queryURL: null,
//------------------------------------------------------------------------
postCreate: function() {
this.inherited(arguments);
// Setting defaults
if (this.searchDelay == null)
this.searchDelay = 500;
if (this.searchAttr == null)
this.searchAttr = "label";
if (this.autoComplete == null)
this.autoComplete = true;
if (this.minKeyCount == null)
this.minKeyCount = 2;
},
escapeRegExp: function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
replaceAll: function (find, replace, str) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
},
startsWith: function (longStr, shortStr) {
return (longStr.match("^" + shortStr) == shortStr)
},
// override search method, count the input length
_startSearch: function (/*String*/ key) {
// If there is not enough text entered, we won't start querying
if (!key || key.length < this.minKeyCount) {
this.closeDropDown();
return;
}
// Deciding if the server needs to be queried
var serverQueryNeeded = false;
if (this.lastServerQueryTerm == null)
serverQueryNeeded = true;
else if (!this.startsWith(key, this.lastServerQueryTerm)) {
// the key does not start with the server queryterm
serverQueryNeeded = true;
}
if (serverQueryNeeded) {
// Creating a query url templated with the autocomplete term
var url = this.replaceAll('${autoCompleteTerm}', key, this.queryURL);
this.store.url = url
// We need to close the store in order to allow the FilteringSelect
// to re-open it with the new query term
this.store.close();
this.lastServerQueryTerm = key;
}
// Calling the super start search
this.inherited(arguments);
}
}
);
});
Notes:
I included some string functions to make it standalone, these should go to their proper places in your JS library.
The JavaScript embedded into the page which uses teh AutoComplete widget:
require([
"dojo/ready",
"dojo/data/ItemFileReadStore",
"gefc/dijit/AutoComplete",
"dojo/parser"
],
function(ready, ItemFileReadStore, AutoComplete) {
ready(function() {
// The initially displayed data (current value, possibly null)
// This makes it possible that the widget does not fire a query against
// the server immediately after initialization for getting a label for
// its current value
var dt = null;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
</g:if>
// If there is no current value, this will have no data
var partnerStore = new ItemFileReadStore(
{ data: dt,
urlPreventCache: true,
clearOnClose: true
}
);
var partnerSelect = new AutoComplete({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
queryURL: '<g:createLink controller="partner"
action="listForAutoComplete"
absolute="true"/>?term=\$\{autoCompleteTerm\}',
store: partnerStore,
searchAttr: "label",
autoComplete: true
},
"technicalContactAC"
);
})
})
Notes:
This is not standalone JavaScript, but generated with Grails on the server side, thus you see <g:if... and other server-side markup in the code). Replace those sections with your own markup.
<g:createLink will result in something like this after server-side page generation: /Limes/partner/listForAutoComplete?term=${autoCompleteTerm}
As of dojo 1.9, I would start by recommending that you replace your ItemFileReadStore by a store from the dojo/store package.
Then, I think dijit/form/FilteringSelect already has the features you need.
Given your requirement to avoid a server round-trip at the initial page startup, I would setup 2 different stores :
a dojo/store/Memory that would handle your initial data.
a dojo/store/JsonRest that queries your controller on subsequent requests.
Then, to avoid querying the server at each keystroke, set the FilteringSelect's intermediateChanges property to false, and implement your logic in the onChange extension point.
For the requirement of triggering the server call after a delay, implement that in the onChange as well. In the following example I did a simple setTimeout, but you should consider writing a better debounce method. See this blog post and the utility functions of dgrid.
I would do this in your GSP page :
require(["dojo/store/Memory", "dojo/store/JsonRest", "dijit/form/FilteringSelect", "dojo/_base/lang"],
function(Memory, JsonRest, FilteringSelect, lang) {
var initialPartnerStore = undefined;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
initialPartnerStore = new Memory({
data : dt
});
</g:if>
var partnerStore = new JsonRest({
target : '<g:createLink controller="partner" action="listForAutoComplete" absolute="true"/>',
});
var queryDelay = 500;
var select = new FilteringSelect({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
store: initialPartnerStore ? initialPartnerStore : partnerStore,
query : { term : ${autoCompleteTerm} },
searchAttr: "label",
autoComplete: true,
intermediateChanges : false,
onChange : function(newValue) {
// Change to the JsonRest store to query the server
if (this.store !== partnerStore) {
this.set("store", partnerStore);
}
// Only query after your desired delay
setTimeout(lang.hitch(this, function(){
this.set('query', { term : newValue }
}), queryDelay);
}
}).startup();
});
This code is untested, but you get the idea...

Set Umbraco Property Editor Input to jQueryUI Datepicker

I'm close but still can't quite get this to work.
I have a new custom property editor that is loading correctly and is doing almost everything expected until I try to set the text field to be a jQuery UI element.
As soon as I add a directive in Angular for setting it to call the jQuery UI datepicker function, I get the following error suggesting it hasn't loaded the jQueryUI script library correctly:
TypeError: Object [object Object] has no method 'datepicker'
Trouble is, I can't see where I should be adding it as the logical places (to my mind, at least) seem to make no difference. Here is the code in full:
function MultipleDatePickerController($scope, assetsService) {
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
//assetsService
// .load([
// "http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"
// ])
// .then(function () {
// //this function will execute when all dependencies have loaded
// });
//load the seperat css for the editor to avoid it blocking our js loading
assetsService.loadCss("/css/jquery-ui.custom.min.css");
if (!$scope.model.value) {
$scope.model.value = [];
}
//add any fields that there isn't values for
//if ($scope.model.config.min > 0) {
if ($scope.model.value.length > 0) {
for (var i = 0; i < $scope.model.value.length; i++) {
if ((i + 1) > $scope.model.value.length) {
$scope.model.value.push({ value: "" });
}
}
}
$scope.add = function () {
//if ($scope.model.config.max <= 0 || $scope.model.value.length < $scope.model.config.max) {
if ($scope.model.value.length <= 52) {
$scope.model.value.push({ value: "" });
}
};
$scope.remove = function (index) {
var remainder = [];
for (var x = 0; x < $scope.model.value.length; x++) {
if (x !== index) {
remainder.push($scope.model.value[x]);
}
}
$scope.model.value = remainder;
};
}
var datePicker = angular.module("umbraco").controller("AcuIT.MultidateController", MultipleDatePickerController);
datePicker.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(function () {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(date);
});
}
});
});
}
}
});
I faced the same problem when adapting a jQuery Date Range Picker for my Date Range Picker package for Umbraco 7. It's frustrating! The problem (I think) is that Angular's ng-model listens for "input" changes to trigger events and so doesn't pick up on a jQuery triggered event.
The way around it I found was to force the input event of the element you wish to update to fire manually, using jQuery's .trigger() event.
For example, the date picker I was using had this code for when a date was changed:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
}
},
I just adapted it to force an input trigger by adding this.element.trigger('input') to the code block, so it now reads:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
this.element.trigger('input');
}
},
This forces Angular to "see" the change and then ng-model is updated. There may well be a more elegant way (as I'm an Angular newbie), but I know this worked for me.
Got it. This is probably a bit of a hack, but it's simple and effective so it's a win nonetheless.
The assetsService call is the key, where I've put code into the deferred .then statement to call jQueryUI's datepicker on any item that has the "jqdp" CSS class:
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
assetsService
.load([
"/App_Plugins/Multidate/jquery-ui.min.js"
])
.then(function () {
//this function will execute when all dependencies have loaded
$('.jqdp').datepicker({ dateFormat: 'dd/mm/yy' });
});
I've then gone and added that class to my view:
<input type="text" jqdatepicker name="item_{{$index}}" ng-model="item.value" class="jqdp" id="dp-{{model.alias}}-{{$index}}" />
Finally, I've added a directive to ensure that dynamically-added items also display a datepicker:
datePicker.directive('jqdatepicker', function () {
return function (scope, element, attrs) {
scope.$watch("jqdatepicker", function () {
try{
$(element).datepicker({ dateFormat: 'dd/mm/yy' });
}
catch(e)
{}
});
};
});
As I said, this is possibly a bit hacky but it achieves the right result and seems like a simple solution.

Kendo Grid Automatically changing Timezone

On my Kendo Grid I recieve date time from server. On the client end, this time is changed to client's timezone and that is displayed. How can I show the same time from the server to the client.
the following is my kendo code for binding the datetime.
columns.Bound(p => p.CreateDate).Format("{0:dd/MM/yyyy hh:mm:ss}").Sortable(true).Width(180);
Since the dates are created on the client when the response from the server is returned - the dates are always created with an offset according to the timezone of the browser
This will help you:
http://www.kendoui.com/code-library/mvc/grid/using-utc-time-on-both-client-and-server-sides.aspx
For example, your client machine is in Sydney and your code is deployed in India.
Saving datetime to DB:
While passing the date time from client side (JavaScript) to server (.NET), pass it as a string, so that it won't get converted to server's time (UK) while saving to the database.
If your datetime field is non editable, then follow solution 1, otherwise solution 2 would be the right choice.
Retrieving from DB:
Solution 1:
Client side Code:
cols.Bound(c => c.ExamDate)
.ClientTemplate(("#= ExamDateString #"))
.Hidden(false)
.Filterable(x => x
.Cell(cell => cell
.ShowOperators(false)
.Operator(StringOperator.eq.ToString())
)
);
Server Side Code:
Server Model property for format:
public string ExamDateString
{
get
{
return ExamDate.HasValue
? ExamDate.Value.ToString("dd/MM/yyyy hh:mm:ss")
: string.Empty;
}
}
Solution 2:
Retrieving from DB:
Client side code:
$.ajax({
type: "POST",
url: '#Url.Action("Controller action method name", "Controller name")',
data: {
"clientMachineTimeZoneOffsetInMinutes ": (new Date()).getTimezoneOffset()
},
success: function (data) {
}
});
Server side code:
//Server Timezone(India) Offset minutes : 330
//Client Timezone(Sydney) Offset minutes : -600
//Difference between Client and Server timezone offset minutes = -270
var serverTimeZoneOffsetInMinutes = DateTimeOffset.Now.Offset.TotalMinutes;
var serverAndClientMachineTimeZoneDifferenceInMinutes = clientMachineTimeZoneOffsetInMinutes + serverTimeZoneOffsetInMinutes;
//Update your date time field with this offset minutes
ExamDate = ExamDate.Value.AddMinutes(serverAndClientMachineTimeZoneDifferenceInMinutes);
Solution 3:
Solution 2 won't handle daylight saving scenario, this would be the ideal solution to handle all scenarios.
Before you return the DataSource result from the controller action method to kendo grid, do the operation below to stop the conversion:
var response = new ContentResult
{
Content = JsonConvert.SerializeObject(value, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local,
DateFormatString = "yyyy-MM-ddTHH:mm:ss"
}),
ContentType = "application/json"
};
return response;
This was my solution.
In the controller I did this:
DateTime time = DateTime.Now();
string x = time.ToString("MM/dd/yyyy hh:mm:ss tt");
And in the View:
columns.Bound(p => p.x);
It is also sortable.
Another option is to use custom JsonResult and convert the date to ISO format.
public class IsoDateJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var isoConvert = new IsoDateTimeConverter();
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
Then change your Controller method to return IsoDateJsonResult instead of ActionResult/JsonResult.
Solution 2 in my above answer, daylight saving hour is getting added if you are not in daylight saving period but you are trying to access the date which falls in daylight saving period, rewriting the solution 2 to support daylight saving period aswell
Client side code to update timezone name:
$.ajax({
type: "POST",
url: '#Url.Action("Controller action method name", "Controller name")',
data: { "timeZoneName": Intl.DateTimeFormat().resolvedOptions().timeZone },
success: function (data) {
}
});
Controller method name to update the timezone in session:
public ActionResult actionMethod(string timeZoneName)
{
Session["timeZoneName"] = Convert.ToString(timeZoneName);
return Json(new { success = true });
}
App config app setting entries:
<add key ="Europe/London" value ="GMT Standard Time" />
Here the key is client time zone name returned by browser and maintained in session here, we have to add entries for all time zone
Place the below code in the controller action method to get the exam date:
var clientMachineTimeZoneName = Convert.ToString(Session["timeZoneName"]);
Get the sever timezone id from config for the corresponding time zone which we got from client side
var timeZoneId = ConfigurationManager.AppSettings[clientMachineTimeZoneName];
TimeZoneInfo clientTimezoneDetails = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var clientTimeZoneOffsetMinutes = clientTimezoneDetails.GetUtcOffset(x.ExamDate.Value).TotalMinutes * -1;
var serverAndClientMachineTimeZoneDifferenceInMinutes = clientTimeZoneOffsetMinutes + TimeZoneInfo.Local.GetUtcOffset(x.ExamDate.Value).TotalMinutes;
//Update your date time field with this offset minutes
ExamDate = ExamDate.Value.AddMinutes(serverAndClientMachineTimeZoneDifferenceInMinutes);
In my case the server is in CST and I am in MST. I needed to persist my SQL Server data to the browser and was getting 02/08/18 23:57 as 02/08/18 22:57 on my Kendo Grid. So I did this, hope it helps:
Checks User / Browser's timezone offset
Gets difference in hours from server timezone offset
Looks at a column on the Kendo Grid with class .dbDate
Grabs the date in that cell (displayedTime) from data object
Uses Moment.js to Convert (convertedTime) it based on the difference (diff) in hours we pass it.
Formats convertedTime to desired format i.e. 02/08/18 23:57
Add 1 to i so the next date in the object gets adjusted
Passes the Grid back the updated date and time.
Must run last on page/grid load/update.
function getDateOffset() {
var date = new Date();
var offset;
var diff;
offset = date.getTimezoneOffset()
if (offset > 360) { //360 = CST
diff = +(offset - 360) / 60
} else if (offset < 360) {
diff = -(360 - offset) / 60
} else {
diff = 0
}
$(".dbDate").each(function (i) {
var grid = $('#Grid').data('kendoGrid');
var displayedTime = grid.dataSource.data()[i].TicketDateTime
var convertedTime = new moment(displayedTime).add(diff, 'hours').toDate();
var originalTime = moment(convertedTime).format("MM/DD/YY HH:mm");
i + 1
$(this).html(originalTime)
})
}

Resources