I am currently using bootstrap datetime picker to handle all date selections in the application. I am using Jquery validation and it works with moment.js.
The input uses a custom knockout binding for the datetime picker.
<div class="col-xs-12 col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Date and Time client received clinical*</label>
<div class="col-md-6" data-bind="visible: SubmittedToClientDateNA() === false">
<input id="SubmittedToClientDate" name="SubmittedToClientDate" autocomplete="off" type="text" class="ph-datetimepicker form-control" data-bind="dateAndTimePicker: SubmittedToClientDate" />
</div>
<div class="col-md-2">
<div class="checkbox">
<label>
<input id="SubmittedToClientDateNA" name="SubmittedToClientDateNA" type="checkbox" data-bind="click: SetSubmittedToClientDate, checked: SubmittedToClientDateNA">N/A
</label>
</div>
</div>
</div>
</div>
Moment.js keeps the date formatted and this js makes sure there is a value.
$("#editAuthorizationInformationForm").validate({
rules: {
SubmittedToClientDate: { required: true }
}
});
The problem I am running into is that when the user types in a date like: '12/20/0008', the validation evaluates this as a valid date. However when the value gets back to the server and tries to save it to sql server it throws an error:
"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value."
Is there a way that I can validate not only the format of the date, but the date itself on the client?
Thank you for your help!
RESOLVED:
I resolved this by adding this custom validator method:
$.validator.addMethod("ValidateDateFormat", function (date) {
var pattern = /(0\d{1}|1[0-2])\/([0-2]\d{1}|3[0-1])\/(19|20)(\d{2})/;
var m = date.match(pattern);
if (!m)
return false;
var d = new Date(date);
// Now let's ensure that the date is not out of index
if (d.getMonth() + 1 == parseInt(m[1], 10) && d.getDate() == parseInt(m[2], 10)) {
return true;
}
return false;
}, "Please enter a valid date");
And applying it to the input field:
$("#editAuthorizationInformationForm").validate({
rules: {
SubmittedToClientDate: { ValidateDateFormat: true, required: true }
}
});