The field 'BirthDate' must be a date MVC 4, internet explorer 11 - asp.net-mvc-4

The same question were asked in this thread The field 'Date' must be a date MVC 4 but I have slightly different problem.I got the error while using internet explorer 11, not able to figure it out.
Here is the property in my model
[Required]
[Display( Name = "Birth Date")]
[DataType(DataType.DateTime)]
public DateTime BirthDate { get; set; }
and jQuery is
$(function () {
dateFormat: $.datepicker.RFC_1123;
$('#BirthDate').attr('readonly', true);
$('#BirthDate').datepicker({ dateFormat: "d/M/yy" });
});
and code for textbox
#Html.TextBoxFor(model => model.RFI.BirthDate, "{0:dd/MMM/yyyy}", new { datepicker = true, #class = "textbox_medium", id = "BirthDate" })
to support this format I wrote the following code in jquery.validate.js file, in the function definition of "date: function (value, element)"
if ($.browser.webkit) {
//ES - Chrome does not use the locale when new Date objects instantiated:
var d = new Date();
return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
}
else {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
The mentioned code works correctly in Crome but doesn't works in internet explorer 11. Frstly it gives the error for webkit, then I changed the definition of a date function (replace code with previous definition) still it gives an error of "The Birthday must be date "

I did a full test of your scenario. The error occurs in IE in jquery.validate.js on the following check:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function( value, element ) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
},
For quick prove you can try to write the following in Console in both IE and Chrome:
new Date('01/Jun/2001');
In Chrome you'll get a valid date and in IE invalid.
To fix the issue - change the format in your date picket to a default one "dd/mm/yy":
$('#BirthDate').datepicker({ dateFormat: "dd/mm/yy" });

Related

How to prevent closing of cell edit mode on validation errors with custom vue components in ag-grid

I have succesfully rendered my own component as the cellEditor and would like and on-leave I would like it to try to validate the value and prevent the closing if it fails.
If I look at this then https://www.ag-grid.com/javascript-grid-cell-editing/#editing-api there's cancelable callback functions for editing. But in this callback function is there a way to access the current instantiated component? I would think that would be the easiest way to handle this.
I'm using vee-validate so the validation function is async, just to keep in mind.
Use Full row editing.
Create a global variable like
var problemRow = -1;
Then Subscribe to this events:
onRowEditingStarted: function (event) {
if (problemRow!=-1 && event.rowIndex!=problemRow) {
gridOptions.api.stopEditing();
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
},
onRowEditingStopped: function (event) {
if (problemRow==-1) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
}
if (problemRow == event.rowIndex) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
else{
problemRow=-1;
}
}
},
I had a similar issue - albeit in AngularJS and the non-Angular mode for ag-grid - I needed to prevent the navigation when the cell editor didn't pass validation.
The documentation is not very detailed, so in the end I added a custom cell editor with a form wrapped around the input field (to handle the niceties such as red highlighting etc), and then used Angular JS validation. That got me so far, but the crucial part was trying to prevent the user tabbing out or away when the value was invalid so the user could at least fix the issue.
I did this by adding a value parser when adding the cell, and then within that if the value was invalid according to various rules, throw an exception. Not ideal, I know - but it does prevent ag-grid from trying to move away from the cell.
I tried loads of approaches to solving this - using the tabToNextCell events, suppressKeyboardEvent, navigateToNextCell, onCellEditingStopped - to name a few - this was the only thing that got it working correctly.
Here's my value parser, for what it's worth:
var codeParser = function (args) {
var cellEditor = _controller.currentCellEditor.children['codeValue'];
var paycodeId = +args.colDef.field;
var paycodeInfo = _controller.paycodes.filter(function (f) { return f.id === paycodeId; })[0];
// Check against any mask
if (paycodeInfo && paycodeInfo.mask) {
var reg = new RegExp("^" + paycodeInfo.mask + '$');
var match = args.newValue.match(reg);
if (!match) {
$mdToast.show($mdToast.simple().textContent('Invalid value - does not match paycode format.').position('top right').toastClass('errorToast'))
.then(function(r) {
_controller.currentCellEditor.children['codeValue'].focus();
});
throw 'Invalid value - does not match paycode format.';
}
}
return true;
};
The _controller.currentCellEditor value is set during the init of the cell editor component. I do this so I can then refocus the control after the error has been shown in the toast:
CodeValueEditor.prototype.init = function (params) {
var form = document.createElement('form');
form.setAttribute('id', 'mainForm');
form.setAttribute('name', 'mainForm');
var input = document.createElement('input');
input.classList.add('ag-cell-edit-input');
input.classList.add('paycode-editor');
input.setAttribute('name', 'codeValue');
input.setAttribute('id', 'codeValue');
input.tabIndex = "0";
input.value = params.value;
if (params.mask) {
input.setAttribute('data-mask', params.mask);
input.setAttribute('ng-pattern','/^' + params.mask + '$/');
input.setAttribute('ng-class',"{'pattern-error': mainForm.codeValue.$error.pattern}");
input.setAttribute('ng-model', 'ctl.currentValue');
}
form.appendChild(input);
this.container = form;
$compile(this.container)($scope);
_controller.currentValue = null;
// This is crucial - we can then reference the container in
// the parser later on to refocus the control
_controller.currentCellEditor = this.container;
$scope.$digest();
};
And then cleared in the grid options onCellEditingStopped event:
onCellEditingStopped: function (event) {
$scope.$apply(function() {
_controller.currentCellEditor = null;
});
},
I realise it's not specifically for your components (Vue.js) but hopefully it'll help someone else. If anyone has done it a better way, I'm all ears as I don't like throwing the unnecessary exception!

CKEditor 5 drag/drop location is invalid

When implementing a custom drag and drop feature, we're seeing an error when trying to insert text at the drop location:
Cannot set selection to given place.
The error points us here, though there isn't any additional information: https://ckeditor.com/docs/ckeditor5/latest/framework/guides/support/error-codes.html#error-model-selection-setTo-not-selectable
The code:
editor.editing.view.document.on('drop', function (evt, data) {
var url = "https://www.url.com";
editor.model.change(function (writer) {
var insertPosition = data.dropRange.start;
var linkedText = writer.createText(url, { linkHref: url });
editor.model.insertContent(linkedText, insertPosition);
});
});
Using editor.model.document.selection.getLastPosition() successfully inserts the text at the most recent cursor position, however for some reason data.dropRange.start is always invalid.

DataTables does not save state of date range search

I am using data tables to display a list of events of different types. Besides the default global text search I need to
1. filter list by event type
2. filter list by date range (show only today -> infinity)
3. Save the state of the table for the the current session.
The state saves as expected except for the date range search which is always reset. Am I missing something or custom search functions are out of the scope of state saving? Here's the relevant code in jQuery:
Fist I add my own search function through the provided method. This works except it's state is not saved
// Extend search()
var threshold_timestamp = xxxxxxxxxxxx // set for beginning of today)
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex) {
var timestamp = parseInt(data[1]); // event date timestamp
if (timestamp > threshold_timestamp) {
return true;
}
return false;
}
);
Then I add a listeners for the select used to switch between the event type options ('','Event','Sports','Dance'...) and the button user to turn on/off the date range filter
$('#filter-by-type').on('change', function() {
table.columns(0).search( $(this).val() ).draw();
});
$('#dt-history').on('click', function() {
// Logic to toggle threshold_timestamp between 0 or value
table.draw();
});
Then I call DataTables
var table = $('#example').DataTable( {
ajax: "datasource.json",
stateSave : true,
stateDuration: -1,
columns: [
{ data: "type"}, //str as 'Sport','Dance'
{ data: "date"} // int as 1528572000
]
});
I managed to scratch my head sideways and "save the date search" using localstorage but that is a hack. On page load I trigger a button click to execute the search so initially the tables seems empty, the "No data available in table" message appears and then the filtered results display. As a second hack I will suppress that message so when there will really be no data... there will be no message :(

Bootstrap time picker issue

I am using Bootstrap time Picker control and store data in DB in string format like 6:30 PM. Now I have an issue when I edit the form and put that value in Bootstrap time Picker control, I got an issue, Any one can help in this regard.
String format is ="6:30 PM" and want to set that string in Bootstrap time Picker control.
EDIT:
I am filling in below format.
blockHoursDetail.FillBlockHours(blockHoursDetail.params.BlockHoursId).done(function (response) {
if (response.status != false) {
var blockHours_detail = JSON.parse(response.BlockHoursFill_JSON);
var self = $("#blockHoursDetail");
utility.bindMyJSON(true, blockHours_detail, false, self);
if (blockHours_detail.chkActive == 'True')
$("#blockHoursDetail #chkActive").attr("checked", true);
else
$("#blockHoursDetail #chkActive").attr("checked", false);
blockHoursDetail.ValidateBlockHours();
$('#frmBlockHoursDetail').data('serialize', $('#frmBlockHoursDetail').serialize());
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
When you return data from the db you should show it like that.
<?php echo date("h:i A",strtotime($time_from_db)); ?>
and if you are facing some problem in initializing of time picker the the specific format then you can use this
$('.timepicker').timepicker('setTime', "6:30 PM");
hope it will help you

dijit.DateTextBox with dojox.widget.Calendar - initialisation

Environment: Dojo.1.8.4
If the DateTextBox does not contain a valid date, I wish to start the calendar popup at a date in the past (it's a date of birth entry box). What is the best way of achieving this?
<div maxlength="12"
data-dojo-type="dijit/form/DateTextBox"
data-dojo-props="required: true, constraints:{min:'1880-01-01',
max: new Date()}, popupClass: 'dojox.widget.Calendar'">
</div>
I want to be able to put a 'startDate' parameter or similar in the above such that the constructor for the popup will pick it up and use it.
It looks as though the dojox.widget._CalendarBase sets the date to the current date in its constructor. (actually seems to set it in both the constructor and the declaration).
NOTE: If you are using the dijit/Calendar dropdown default then use the dropDownDefaultValue property as #vogomatix says in the other answer.
The following is if you are using the dojox/widget/Calendar for the dropdown.
By default the popup is set to the current value of the textbox and if null, it will use the current date.
You can do
1) set the value of the text box to what you want the default to be
OR
2) use aspects to set the value in the calendar when it is opened.
require([
'dojo/dom',
'dojo/aspect',
'dijit/form/DateTextBox',
'dojox/widget/Calendar'
], function(dom, aspect, DateTextBox, Calendar){
var dt = new DateTextBox({ popupClass: Calendar }, dom.byId('dtText'));
aspect.after(dt, 'openDropDown', function() {
// only default if there is no value
if(dt.get('value') == null) {
// Do not set the text box when changing value,
// so temporarily override the onchange function
var oldOnChange = dt.dropDown.onChange;
dt.dropDown.onChange = function(){};
dt.dropDown.set('value', new Date(1980, 7, 4)); // default to August 4th, 1980
dt.dropDown.onChange = oldOnChange;
}
});
});
See it in action:
http://jsfiddle.net/cswing/kQYhQ/
One solution is to set dropDownDefaultValue, which works with the standard calendar.
var dt = new DateTextBox({dropDownDefaultValue: new Date( 1950,1,1)},
dom.byId('dtText'));
dropDownDefaultValue gets passed to the calender in the form of currentFocus by the popup. Unfortunately dojox.widget.Calendar does not recognise currentFocus and the way round that is to either extend the class to do so, or to use the aspect method above.
This is how to extend the dojox.widget.Calendar in order to accept the currentFocus passed by the popup. Like the aspect method above, it temporarily disables onChange in order to prevent the value being placed in the parent DateTextBox
define([
"dojo/_base/declare",
"dojox/widget/Calendar"
], function(declare, calendar){
return declare("my.dijit.Calendar", [calendar], {
postCreate: function() {
this.inherited(arguments);
var oldOnChange = this.onChange;
this.onChange = function(){};
this.set('value', this.parseInitialValue( this.currentFocus));
this.onChange = oldOnChange;
}
});
});