InvalidStateError: The object is in an invalid state in Safari

The issue:

This issue might occur in my different reasons. In our case this happened on Safari browser. We were trying to set a default value of a date type input element. We wanted to set the current date to the input field. The JavaScript we wrote that triggered this issue.

InvalidStateError: The object is in an invalid state

The reason:

This error happened on Safari browser because of the following JavaScript we wrote:

//DOM element 
<input type="date" id="datePicker">
// JavaScript
document.getElementById('datePicker').valueAsDate = new Date();
// Error
InvalidStateError: The object is in an invalid state

The solution:

We can solve the above issue in many ways. We can extend the Date object and write our custom method to set a default date value. Following is one approach to solve this issue:

Approach #1

Date.prototype.setDefaultDate = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

// JavaScript call: 
document.getElementById('datePicker').value = new Date().setDefaultDate();

// jQuery call: 
$('#datePicker').val(new Date().setDefaultDate());

Approach #2

var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" + ("0" + d.getDate()).slice(-2);   
document.getElementById('datePicker').value = datestring;
Share